code:
/*
Copyright (c) 2011 Elektrobit (EB), All rights reserved.
Contact: oss-devel@elektrobit.com

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Elektrobit (EB) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Elektrobit (EB) ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Elektrobit (EB) BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package eu.licentia.necessitas.mobile;

import java.io.IOException;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.view.View;
import eu.licentia.necessitas.industrius.QtApplication;

public class QtFeedback extends BroadcastReceiver{
    private static View m_view=null;
    private AudioManager m_audioManager=null;
    private Vibrator m_vibrator=null;
    private int m_vibrateDuration=0;
    private int m_vibrateperiod=0;
    private int m_hapticConstant = 0;
    private MediaPlayer m_mediaPlayer= null;
    private int m_resumeTime=0;
    private AlarmManager m_alarmManager=null;
    private PendingIntent m_pendingIntent=null;

    public QtFeedback() {
        m_alarmManager = (AlarmManager) QtApplication.mainActivity().getSystemService(Activity.ALARM_SERVICE);
        m_mediaPlayer= new MediaPlayer();
        m_mediaPlayer.setLooping(false);
        m_vibrator =(Vibrator) QtApplication.mainActivity().getSystemService(Activity.VIBRATOR_SERVICE);
        m_audioManager = (AudioManager)QtApplication.mainActivity().getSystemService(Activity.AUDIO_SERVICE);
        m_view = QtApplication.mainView();
    }

    public void playThemeEffect(int soundConstant)
    {
        m_audioManager.playSoundEffect(soundConstant);
    }

    public void loadMusicFile(String path)
    {
        m_mediaPlayer.reset();
        try {
            m_mediaPlayer.setDataSource(path);
            m_mediaPlayer.prepare();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setFileState(int state)
    {
        switch (state) {
        case 0:
            m_mediaPlayer.pause();
            break;

        case 1:
            m_mediaPlayer.stop();
            try {
                    m_mediaPlayer.prepare();
            } catch (IllegalStateException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            }
            m_mediaPlayer.seekTo(0);
            break;

        case 2:
        case 3:
            m_mediaPlayer.start();
            break;

        default:
            break;
        }
    }

    public void setVibrateState(int state)
    {
        long vibratePattern[] = {0,0,0};
        if(m_vibrateperiod == -1 || m_vibrateperiod == 0)
        {
            if(m_resumeTime == 0)
            {
                long nonPeriodPattern[] = {(long) 0,(long) m_vibrateDuration};
                vibratePattern = nonPeriodPattern;
            }
            else
            {
                long nonPeriodPattern[] = {(long) 0,(long) m_resumeTime};
                vibratePattern = nonPeriodPattern;
            }
        }
        else
        {
            long periodPattern[] = {(long) 0,(long) m_vibrateperiod,(long) m_vibrateperiod};
            vibratePattern = periodPattern;
        }

        switch(state)
        {
        case 0:
        case 1:
                m_vibrator.cancel();
                QtApplication.mainActivity().unregisterReceiver(this);
                break;
        case 2:
        case 3:
            registerReciever();
            if(m_vibrateperiod == -1 || m_vibrateperiod == 0)
            {
                m_vibrator.vibrate(vibratePattern,-1);
            }
            else
            {
                if(m_resumeTime == 0)
                {
                    m_alarmManager.set(AlarmManager.RTC_WAKEUP,(System.currentTimeMillis()+m_vibrateDuration), m_pendingIntent);
                }
                else
                {
                    m_alarmManager.set(AlarmManager.RTC_WAKEUP,(System.currentTimeMillis()+m_resumeTime), m_pendingIntent);
                }
                m_vibrator.vibrate(vibratePattern,0);
            }
        }
    }

    public void setVibraDuration(int duration,int period,int resumeTime)
    {
        m_vibrateDuration = duration;
        m_vibrateperiod = period;
        m_resumeTime = resumeTime;
    }

    public void registerReciever()
    {
        IntentFilter filter = new IntentFilter("Alarm");
        QtApplication.mainActivity().registerReceiver(this , filter);
        Intent intent = new Intent("Alarm");
        m_pendingIntent = PendingIntent.getBroadcast(QtApplication.mainActivity(), 0, intent, 0);
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        m_vibrator.cancel();
        QtApplication.mainActivity().unregisterReceiver(this);
    }

    public void setHapticFeedback(boolean enabled)
    {

        final boolean enable = enabled;
        QtApplication.mainActivity().runOnUiThread(new Runnable() {
            public void run() {
                m_view.setHapticFeedbackEnabled(enable);
            }
        });

    }

    public void performHapticFeedback()
    {
        QtApplication.mainActivity().runOnUiThread(new Runnable() {
            public void run() {
                m_view.performHapticFeedback(m_hapticConstant);
            }
        });
    }

    public void setHapticIntensity(int hapticConst)
    {
        m_hapticConstant = hapticConst;
    }
}


code:
/*
Copyright (c) 2011 Elektrobit (EB), All rights reserved.
Contact: oss-devel@elektrobit.com

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Elektrobit (EB) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Elektrobit (EB) ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Elektrobit (EB) BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package eu.licentia.necessitas.mobile;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import eu.licentia.necessitas.industrius.QtApplication;

import android.app.Activity;
import android.hardware.GeomagneticField;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.util.Log;

class QtSatInfo
{
    @SuppressWarnings("unused")
    private int m_prnNumber;
    @SuppressWarnings("unused")
    private float m_signalStrength;
    @SuppressWarnings("unused")
    private float m_elevation;
    @SuppressWarnings("unused")
    private float m_azimuth;

    public QtSatInfo (int prnNumber,float signalStength,float elevation,float azimuth)
    {
        m_prnNumber=prnNumber;
        m_signalStrength=signalStength;
        m_elevation=elevation;
        m_azimuth=azimuth;
    }
}

public class QtLocation implements LocationListener ,GpsStatus.Listener
{
    private LocationManager m_locationManager;
    private long m_getMinTime;
    private LocationListener m_myself;
    private GpsStatus m_status;
    private static final String GPS=LocationManager.GPS_PROVIDER;
    private static final String NETWORK=LocationManager.NETWORK_PROVIDER;
    private ArrayList<String> m_providerChossenList=new ArrayList<String>();

    public QtLocation ()
    {
        // Get the location manager
        m_locationManager = (LocationManager) QtApplication.mainActivity().getSystemService(Activity.LOCATION_SERVICE);
        m_status = m_locationManager.getGpsStatus(null);
        m_providerChossenList.add(GPS);
        m_providerChossenList.add(NETWORK);
        m_myself=this;
    }

    public double[] lastKnownPosition(int fromSatellitePositioningMethodsOnly)
    {
        double[] getData=new double[7];
        Location location=null;
        Location networkLastLocation=null;
        Location gpsLastLocation=null;
        try
        {
            networkLastLocation=m_locationManager.getLastKnownLocation(GPS);
            gpsLastLocation=m_locationManager.getLastKnownLocation(NETWORK);
            if(fromSatellitePositioningMethodsOnly == 1)
            {
                location=gpsLastLocation;
            }
            else
            {
                location=(networkLastLocation.getTime()>gpsLastLocation.getTime())
                                                    ?networkLastLocation:gpsLastLocation;
            }

            GeomagneticField geomagneticField = new GeomagneticField((float)location.getLatitude(),
                    (float)location.getLongitude(), (float)location.getAltitude(),location.getTime());

            getData[0]=location.getAltitude();
            getData[1]=location.getLatitude();
            getData[2]=location.getLongitude();
            getData[3]=location.getTime();
            getData[4]=geomagneticField.getDeclination();
            getData[5]=location.getSpeed();
            getData[6]=location.getBearing();
        }
        catch(Exception e)
        {
            Log.i("QtLocation","LastknownLocation not available");
        }

        return getData;
    }

    public long supportedPositiongMethods ()
    {
        long supportedPositioningMethods=0;
        List<String> providers=null;
        providers=m_locationManager.getProviders(false);
        Iterator<String> it=providers.iterator();
        while(it.hasNext())
        {
            supportedPositioningMethods|=positioningMethods(it.next());
        }
        return supportedPositioningMethods;
    }

    private long positioningMethods (String provider)
    {
        long positioningMethod=0;
        LocationProvider providerInfo=m_locationManager.getProvider(provider);
        if(providerInfo.requiresSatellite())
        {
            positioningMethod=0x000000ff;//Satellite-based positioning methods such as GPS
        }
        if(providerInfo.requiresCell()||providerInfo.requiresNetwork())
        {
            //0xffffff00 is for other-based positioning methods
            //0xffffffff is for all methods
            positioningMethod|= 0xffffff00;
        }
        return positioningMethod;
    }

    public void requestUpdates(long minTime)
    {
        m_getMinTime=minTime;
        QtApplication.mainActivity().runOnUiThread(new Runnable() {

            public void run() {
                // TODO Auto-generated method stub
                m_locationManager.requestLocationUpdates(GPS, m_getMinTime, 0,m_myself);
                m_locationManager.requestLocationUpdates(NETWORK,m_getMinTime, 0,m_myself);
            }
        });

    }

    public void requestSatelliteUpdates()
    {
        QtApplication.mainActivity().runOnUiThread(new Runnable() {

            public void run() {
                // TODO Auto-generated method stub
                m_locationManager.addGpsStatusListener((GpsStatus.Listener) m_myself);
            }
        });

    }

    public void disableUpdates()
    {
        m_locationManager.removeUpdates(this);
    }

    public void disableSatelliteUpdates ()
    {
        m_locationManager.removeGpsStatusListener(this);
    }

    public void onLocationChanged(Location location)
    {
        // TODO Auto-generated method stub
        double[] getData=new double[8];
        GeomagneticField geomagneticField = new GeomagneticField((float)location.getLatitude(),
                (float)location.getLongitude(), (float)location.getAltitude(),location.getTime());

        getData[0]=location.getLatitude();
        getData[1]=location.getLongitude();
        getData[2]=location.getAltitude();
        getData[3]=location.getTime();
        //these are for attributes
        getData[4]=location.getBearing();//bearing
        getData[5]=location.getSpeed();//ground speed
        getData[6]=geomagneticField.getDeclination();//magnetic dip
        getData[7]=location.getAccuracy();//vertical and horizontal accuracy

        locationDataUpdated(getData,location.getProvider());
    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    public void onGpsStatusChanged(int event) {

        switch(event)
        {
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                m_locationManager.getGpsStatus(m_status);
                Iterable<GpsSatellite> iSatellite=m_status.getSatellites();
                Iterator<GpsSatellite> iterator=iSatellite.iterator();
                ArrayList<QtSatInfo> satInfo=new ArrayList<QtSatInfo>();
                int index=0;
                while(iterator.hasNext())
                {
                    GpsSatellite gpsSat=iterator.next();

                    satInfo.add(new QtSatInfo(gpsSat.getPrn(),gpsSat.getSnr(),
                            gpsSat.getElevation(), gpsSat.getAzimuth()));
                    index++;
                }

                if(0!=index)
                    gpsSatelliteDataUpdated(satInfo.toArray());
                break;
        }

    }

    public static native void locationDataUpdated(double getData[],String providerName);

    public static native void gpsSatelliteDataUpdated(Object satinfo[]);
}

repo_name: snapshot/uds

license: mit


code:
/*
Copyright (c) 2011 Elektrobit (EB), All rights reserved.
Contact: oss-devel@elektrobit.com

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Elektrobit (EB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Elektrobit (EB) ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Elektrobit
(EB) BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package eu.licentia.necessitas.mobile;

import java.io.IOException;
import android.media.MediaPlayer;

class QtMediaPlayer implements MediaPlayer.OnCompletionListener,MediaPlayer.OnBufferingUpdateListener
{
    int m_uniqueID;
    private static MediaPlayer m_mediaPlayer=null;

    public QtMediaPlayer(int uniqueID)
    {
        m_uniqueID = uniqueID;
    }

    private int setQtMediaPlayer(String path)
    {
        m_mediaPlayer = new MediaPlayer();
        m_mediaPlayer.setOnBufferingUpdateListener(this);
        m_mediaPlayer.setOnCompletionListener(this);
        m_mediaPlayer.reset();
        try {
            m_mediaPlayer.setDataSource(path);
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            m_mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return m_mediaPlayer.getDuration();
    }

    private int getCurrentPosition()
    {
        if(m_mediaPlayer==null)
        {
            return 0;
        }
        return m_mediaPlayer.getCurrentPosition();
    }

    private void play()
    {
        if(m_mediaPlayer!=null)
        {
            m_mediaPlayer.start();
        }
    }

    private void pause()
    {
        if(m_mediaPlayer!=null)
        {
            m_mediaPlayer.pause();
        }
    }
    private void stop()
    {
        if(m_mediaPlayer!=null)
        {
            m_mediaPlayer.stop();
        }
    }
    private void seekTo(int mSec)
    {
        if(m_mediaPlayer!=null)
        {
            m_mediaPlayer.seekTo(mSec);
        }
    }
    private void setVolume(float lVolume,float rVolume)
    {
        if(m_mediaPlayer!=null)
        {
            float vol= lVolume/100;
            m_mediaPlayer.setVolume(vol,vol);
        }
    }

    private void resume()
    {
        if(m_mediaPlayer!=null)
        {
            m_mediaPlayer.start();
        }
    }
    private void release()
    {
        if(m_mediaPlayer!=null)
        {
            m_mediaPlayer.release();
        }
    }

    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        bufferProgress(percent,m_uniqueID);
    }

    public void onCompletion(MediaPlayer mp) {
        playCompleted(m_uniqueID);
    }

    public static native void playCompleted(int uniqueID);
    public static native void bufferProgress(int percent,int uniqueID);

}


code:
/*
Copyright (c) 2011 Elektrobit (EB), All rights reserved.
Contact: oss-devel@elektrobit.com

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Elektrobit (EB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Elektrobit (EB) ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Elektrobit
(EB) BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.licentia.necessitas.mobile;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import eu.licentia.necessitas.industrius.QtApplication;

public class QtSensors implements SensorEventListener
{
    private static SensorManager m_SensorManager;
    private Sensor m_Sensor;
    private int m_uniqueId=-1;
    private int m_sensorType;
    private List<Sensor> getListSensor;

    public QtSensors(int uniqueID,int datarate,int sensorType)
    {
        m_uniqueId=uniqueID;
        m_sensorType=sensorType;
        getListSensor=new ArrayList<Sensor>();
        getListSensor=m_SensorManager.getSensorList(m_sensorType);
        if(!getListSensor.isEmpty())
        {
            start(datarate);
        }
        else
        {
            Log.i("QtSensors", "Sensor not avialable");
        }
    }

    private static void registerSensors ()
    {
        m_SensorManager = (SensorManager)QtApplication.mainActivity().getSystemService(Activity.SENSOR_SERVICE);
    }

    private void start (int datarate)
    {
        m_Sensor = m_SensorManager.getDefaultSensor(m_sensorType);
        m_SensorManager.registerListener(this, m_Sensor,datarate);
    }

    public void stop ()
    {
        if(!getListSensor.isEmpty())
        {
            m_SensorManager.unregisterListener(this, m_Sensor);
        }
    }

    public void onSensorChanged(SensorEvent event) {

        if(event.sensor.getType()==Sensor.TYPE_PROXIMITY)
        {
            event.values[0]=(event.values[0]<event.sensor.getMaximumRange())?1:0;
        }
        slotDataAvailable(event.values,event.timestamp,event.accuracy,m_uniqueId);
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public static native void slotDataAvailable(float data[],long timeEvent,
            int accuracy,int uniqueID);

}


code:
/*
Copyright (c) 2011 Elektrobit (EB), All rights reserved.
Contact: oss-devel@elektrobit.com

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Elektrobit (EB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Elektrobit (EB) ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Elektrobit
(EB) BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package eu.licentia.necessitas.mobile;

import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.app.KeyguardManager;
//@ANDROID-5
//QtCreator import android.bluetooth.BluetoothAdapter;
//@ANDROID-5
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
//@ANDROID-5
//QtCreator import android.telephony.SignalStrength;
//@ANDROID-5
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.DisplayMetrics;
//@ANDROID-5
//QtCreator import android.util.Log;
//@ANDROID-5
import android.view.Display;
//@ANDROID-5
//QtCreator import android.view.Surface;
//@ANDROID-5
import eu.licentia.necessitas.industrius.QtApplication;

class BatteryInfo
{
    @SuppressWarnings("unused")
    private char m_batteryStatus;
    @SuppressWarnings("unused")
    private int m_chargerType;
    int m_chargingState;
    @SuppressWarnings("unused")
    private int m_maxBars;
    @SuppressWarnings("unused")
    private int m_remainingCapacityBars;
    @SuppressWarnings("unused")
    private int m_remainingCapacityPercent;
    @SuppressWarnings("unused")
    private int m_voltage;

    BatteryInfo(char batteryStatus,int chargerType,int chargingState,int maxBars,int remainingCapacityBars,int remainingCapacityPercent,int voltage)
    {

        m_batteryStatus=batteryStatus;
        m_chargerType=chargerType;
        m_chargingState=chargingState;
        m_maxBars=maxBars;
        m_remainingCapacityBars=remainingCapacityBars;
        m_remainingCapacityBars=remainingCapacityBars;
        m_remainingCapacityPercent=remainingCapacityPercent;
        m_voltage=voltage;
    }
}

public class QtSystemInfo
{
    private static Map<Integer,Integer> m_chargerType;
    private static HashMap<Integer,Integer> m_Chargingstatus;
    private IntentFilter m_batteryIntentFilter;
    private BroadcastReceiver m_batteryInfoBroadcastReceiver;

    private KeyguardManager m_keyguardManager;
    private KeyguardManager.KeyguardLock m_keygaurdLock;
    private PowerManager m_powerManager;
    private WakeLock m_wakeLock;

//@ANDROID-5
//QtCreator     private  BluetoothAdapter m_bluetoothAdapter;
//@ANDROID-5
    private TelephonyManager m_telephonyManager;
    private BroadcastReceiver m_deviceInfoBroadcastReceiver;
    //display
    private Display m_display;
    private DisplayMetrics m_displaymatrics;
    private BroadcastReceiver m_displayInfoBroadcastReceiver;

    private BroadcastReceiver m_storageInfoBroadcastReceiver;

    public static final int BRIGHTNESS_OFF = 0;//Brightness value for fully off
    public static final int BRIGHTNESS_DIM = 20;//Brightness value for dim backlight
    public static final int BRIGHTNESS_ON = 255;//Brightness value for fully on

    //network
    private ConnectivityManager m_connectivityManager;
    private WifiManager m_wifiManager;
    private PhoneStateListener m_phoneStateListener;
    private BroadcastReceiver m_networkBroadcastReceiver;

    //system general info
    private BroadcastReceiver m_generalSystemInfo;
    QtSystemInfo ()
    {
        QtApplication.mainActivity().runOnUiThread(new Runnable() {

            public void run() {
//@ANDROID-5
//QtCreator                 m_bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//@ANDROID-5
            }
        });
        m_powerManager = (PowerManager)QtApplication.mainActivity().getSystemService(Context.POWER_SERVICE);
        m_telephonyManager= (TelephonyManager) QtApplication.mainActivity().getSystemService(Context.TELEPHONY_SERVICE);
        disableLock();
    }

    public void initScreensaver ()
    {
        m_wakeLock = m_powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "QSystemScreenSaver");
    }

    private void disableLock ()
    {
        m_keyguardManager=(KeyguardManager)QtApplication.mainActivity().getSystemService(Context.KEYGUARD_SERVICE);
        m_keygaurdLock=m_keyguardManager.newKeyguardLock("QSystemScreenSaver");
        m_keygaurdLock.disableKeyguard();
    }
    public void setScreenSaverInhibit ()
    {
        //m_keygaurdLock.disableKeyguard();
        m_wakeLock.acquire();
    }

    public void DisableScreenSaverInhibit()
    {
        m_wakeLock.release();
        //m_keygaurdLock.reenableKeyguard();
    }

    public void initBattery()
    {
        //Battery Information
        m_chargerType=new HashMap<Integer, Integer>();
        m_chargerType.put(BatteryManager.BATTERY_PLUGGED_AC,1);
        m_chargerType.put(BatteryManager.BATTERY_PLUGGED_USB, 2);
        m_chargerType.put(0, 0);

        createBatteryBroadcastReceiver ();

        //only the first two are supported in qt
        m_Chargingstatus=new HashMap<Integer, Integer>();
        m_Chargingstatus.put(BatteryManager.BATTERY_STATUS_NOT_CHARGING,0);
        m_Chargingstatus.put(BatteryManager.BATTERY_STATUS_CHARGING, 1);
        m_Chargingstatus.put(BatteryManager.BATTERY_STATUS_DISCHARGING, -1);
        m_Chargingstatus.put(BatteryManager.BATTERY_STATUS_FULL, -1);
        m_Chargingstatus.put(BatteryManager.BATTERY_STATUS_UNKNOWN, -1);
        m_batteryIntentFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        m_batteryIntentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        m_batteryIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        QtApplication.mainActivity().registerReceiver(m_batteryInfoBroadcastReceiver,m_batteryIntentFilter);
        //end of battery
    }

    public void exitBattery ()
    {
        QtApplication.mainActivity().unregisterReceiver(m_batteryInfoBroadcastReceiver);
    }

    private void createBatteryBroadcastReceiver ()
    {
//@ANDROID-5
//QtCreator         m_batteryInfoBroadcastReceiver=new BroadcastReceiver() {
//QtCreator             @Override
//QtCreator             public void onReceive(Context context, Intent intent)
//QtCreator             {
//QtCreator
//QtCreator                 if((intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)))
//QtCreator                 {
//QtCreator                     char batteryStatus;
//QtCreator                     int level=intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
//QtCreator                     int maxLevel=intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
//QtCreator                     float batteryStatusPercentage;
//QtCreator
//QtCreator                         batteryStatusPercentage=(maxLevel ==0)?-1:(level*100)/maxLevel;//check whether is there a scale
//QtCreator                         if(batteryStatusPercentage==-1)
//QtCreator                         {
//QtCreator                             batteryStatus='?';
//QtCreator                         }
//QtCreator                         if (batteryStatusPercentage ==0)
//QtCreator                         {
//QtCreator                             batteryStatus=0;
//QtCreator                         }
//QtCreator                         else if (batteryStatusPercentage <= 3)
//QtCreator                         {
//QtCreator                             batteryStatus=1;
//QtCreator                         }
//QtCreator                         else if (batteryStatusPercentage <=10)
//QtCreator                         {
//QtCreator                             batteryStatus=2;
//QtCreator                         }
//QtCreator                         else if (batteryStatusPercentage <40)
//QtCreator                         {
//QtCreator                             batteryStatus=3;
//QtCreator                         }
//QtCreator                         else if (batteryStatusPercentage <100)
//QtCreator                         {
//QtCreator                             batteryStatus=4;
//QtCreator                         }
//QtCreator                         else
//QtCreator                         {
//QtCreator                             batteryStatus=5;
//QtCreator                         }
//QtCreator
//QtCreator                         int chargerType=m_chargerType.get(intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0));
//QtCreator                         int chargingState=m_Chargingstatus.get(intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1));//check battery charging status
//QtCreator                         int maxBars=maxLevel;
//QtCreator                         int remainingCapacityBars=maxBars-level;
//QtCreator                         int remainingCapacityPercent=(int)batteryStatusPercentage;
//QtCreator                         int voltage=intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
//QtCreator                         BatteryInfo batteryInfo=new BatteryInfo(batteryStatus, chargerType,
//QtCreator                                 chargingState, maxBars, remainingCapacityBars,
//QtCreator                                 remainingCapacityPercent, voltage);
//QtCreator                         BatteryDataUpdated(batteryInfo);
//QtCreator                 }
//QtCreator
//QtCreator             }
//QtCreator         };
//@ANDROID-5
    }
    public void initDevice ()
    {
        createDeviceInfoBroadcastReceiver ();
        QtApplication.mainActivity().registerReceiver(m_deviceInfoBroadcastReceiver,new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION));
//@ANDROID-5
//QtCreator         QtApplication.mainActivity().registerReceiver(m_deviceInfoBroadcastReceiver,new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
//@ANDROID-5
        QtApplication.mainActivity().registerReceiver(m_deviceInfoBroadcastReceiver,new IntentFilter(Intent.ACTION_SCREEN_OFF));
        QtApplication.mainActivity().registerReceiver(m_deviceInfoBroadcastReceiver,new IntentFilter(Intent.ACTION_SCREEN_ON));

    }

    public void exitDevice ()
    {
        try
        {
            QtApplication.mainActivity().unregisterReceiver(m_deviceInfoBroadcastReceiver);
        }
        catch(Exception e)
        {

        }
    }

    private void createDeviceInfoBroadcastReceiver ()
    {
        m_deviceInfoBroadcastReceiver=new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent)
            {
//@ANDROID-5
//QtCreator                 if((intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)))
//QtCreator                 {
//QtCreator                     boolean state=false;
//QtCreator                     switch(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR))
//QtCreator                     {
//QtCreator                         case BluetoothAdapter.STATE_OFF:
//QtCreator                             state=false;
//QtCreator                             break;
//QtCreator                         case BluetoothAdapter.STATE_ON:
//QtCreator                             state=true;
//QtCreator                             break;
//QtCreator                         default:
//QtCreator                             return;
//QtCreator
//QtCreator                     }
//QtCreator                     bluetoothStateChanged(state);
//QtCreator                 }
//@ANDROID-5

                if((intent.getAction().equals(AudioManager.RINGER_MODE_CHANGED_ACTION)))
                {
                        int mode=intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1);
                        profileChanged(mode);
                }

                if((intent.getAction().equals(Intent.ACTION_SCREEN_ON)))
                {
                    deviceLocked(false);
                }
                if((intent.getAction().equals(Intent.ACTION_SCREEN_OFF)))
                {
                    deviceLocked(true);

                }
            }
        };
    }

//@ANDROID-5
//QtCreator     public boolean bluetoothPowerState ()
//QtCreator     {
//QtCreator         boolean state;
//QtCreator
//QtCreator         switch(m_bluetoothAdapter.getState())
//QtCreator         {
//QtCreator             case BluetoothAdapter.STATE_OFF:
//QtCreator                 state=false;
//QtCreator                 break;
//QtCreator             case BluetoothAdapter.STATE_ON:
//QtCreator                 state=true;
//QtCreator                 break;
//QtCreator             default:
//QtCreator                 state=false;
//QtCreator         }
//QtCreator         return state;
//QtCreator     }
//QtCreator
//QtCreator     public int lockStatus ()
//QtCreator     {
//QtCreator         if(m_powerManager.isScreenOn())
//QtCreator         {
//QtCreator             return 1;
//QtCreator         }
//QtCreator         else
//QtCreator         {
//QtCreator             return 3;
//QtCreator         }
//QtCreator     }
//QtCreator     public boolean isDeviceLocked ()
//QtCreator     {
//QtCreator         if(m_powerManager.isScreenOn())
//QtCreator         {
//QtCreator             return false;
//QtCreator         }
//QtCreator         else
//QtCreator         {
//QtCreator             return true;
//QtCreator         }
//QtCreator     }
//@ANDROID-5

    public String imei ()
    {
        String imei="";
        if(m_telephonyManager.getDeviceId()!=null)
        {
            imei=m_telephonyManager.getDeviceId();
        }
        else
        {
            imei="";
        }
        return imei;
    }

    public String imsi ()
    {
        String imsi="";
        if(m_telephonyManager.getSubscriberId()!=null)
        {
            imsi=m_telephonyManager.getDeviceId();
        }
        else
        {
            imsi="";
        }
        return imsi;
    }

    public boolean isKeyboardFlipOpened ()
    {
        Configuration configuration=new Configuration();
        if(configuration.hardKeyboardHidden==Configuration.HARDKEYBOARDHIDDEN_YES)
        {
                return true;
        }
        else
        {
                return false;
        }
    }

    public int inputMethodType ()
    {
        Configuration configuration=new Configuration();
        int inputMethod=0x0000001;//by default the keys will have a key and buttons
//@ANDROID-8
//QtCreator     PackageManager pm=QtApplication.mainActivity().getPackageManager();
//QtCreator         if(pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN))
//QtCreator         {
//QtCreator             inputMethod|=0x0000008;
//QtCreator         }
//QtCreator         if((pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)) ||
//QtCreator                 (pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)))
//QtCreator         {
//QtCreator             inputMethod|=0x0000010;
//QtCreator         }
//@ANDROID-8
        if(configuration.keyboard==Configuration.KEYBOARD_QWERTY)
        {
            inputMethod|=0x0000004;
        }
        if(configuration.keyboard==Configuration.KEYBOARD_12KEY)
        {
            inputMethod|=0x0000002;
        }
        return inputMethod;
    }

    public int keyboardType ()
    {
        int keyboardType=0;
        Configuration configuration=new Configuration();
        if(configuration.keyboard==Configuration.KEYBOARD_QWERTY)
        {
            keyboardType|=0x0000008;
        }
        if(configuration.keyboard==Configuration.KEYBOARD_12KEY)
        {
            keyboardType|=0x0000002;
        }
        if((configuration.touchscreen==Configuration.TOUCHSCREEN_STYLUS)
            ||(configuration.touchscreen==Configuration.TOUCHSCREEN_FINGER))
        {
            keyboardType|=0x0000001;
        }
        return keyboardType;
    }

    public String manufacturer ()
    {
        return Build.MANUFACTURER;
    }

    public String model ()
    {
        return Build.MODEL;
    }

    public String productName ()
    {
        return Build.PRODUCT;
    }

    public int simStatus ()
    {
        int status=0;
        switch(m_telephonyManager.getSimState())
        {

            case TelephonyManager.SIM_STATE_READY:
                status=1;
                break;
            case TelephonyManager.SIM_STATE_PIN_REQUIRED:
            case TelephonyManager.SIM_STATE_PUK_REQUIRED:
            case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                status=3;
                break;
            default:
                status=0;
        }
        return status;
    }

    //display
    public void initDisplay ()
    {
        createDisplayInfoBroadcastReceiver ();
        m_display=QtApplication.mainActivity().getWindowManager().getDefaultDisplay();
        m_displaymatrics=new DisplayMetrics();
        QtApplication.mainActivity().getWindowManager().getDefaultDisplay().getMetrics(m_displaymatrics);
        QtApplication.mainActivity().registerReceiver(m_displayInfoBroadcastReceiver,new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
    }

    public void exitDisplay ()
    {
        QtApplication.mainActivity().unregisterReceiver(m_displayInfoBroadcastReceiver);
    }

    private void createDisplayInfoBroadcastReceiver ()
    {
//@ANDROID-8
//QtCreator         m_displayInfoBroadcastReceiver=new BroadcastReceiver() {
//QtCreator
//QtCreator             @Override
//QtCreator             public void onReceive(Context context, Intent intent)
//QtCreator             {
//QtCreator                 if((intent.getAction().equals(Intent.ACTION_CONFIGURATION_CHANGED)))
//QtCreator                 {
//QtCreator                     Log.i("QtSystemInfo", "orientationchage wont be called");
//QtCreator                     int orientation; /// ?!?!?!
//QtCreator
//QtCreator                     switch(m_display.getRotation())
//QtCreator                     {
//QtCreator                         case Surface.ROTATION_270:
//QtCreator                         case Surface.ROTATION_90:
//QtCreator                             orientation= 1;
//QtCreator                             break;
//QtCreator
//QtCreator                         case Surface.ROTATION_0:
//QtCreator                         case Surface.ROTATION_180:
//QtCreator                             orientation= 2;
//QtCreator                             break;
//QtCreator
//QtCreator                         default:
//QtCreator                             orientation=0;
//QtCreator                             break;
//QtCreator                     }
//QtCreator                 }
//QtCreator             }
//QtCreator         };
//@ANDROID-8
    }

    public float getDPIHeight  ()
    {
        return m_displaymatrics.ydpi;
    }

    public float getDPIWidth ()
    {
        return m_displaymatrics.xdpi;
    }

    public float physicalHeight ()
    {
        float heightInInches = (float) (m_displaymatrics.heightPixels / m_displaymatrics.ydpi * 25.4);
        return heightInInches;
    }

    public float physicalWidth ()
    {
        float widthInInches = (float) (m_displaymatrics.widthPixels / m_displaymatrics.xdpi*25.4);
        return widthInInches;
    }

    public int orientation ()
    {
//@ANDROID-8
//QtCreator         switch(m_display.getRotation())
//QtCreator         {
//QtCreator             case Surface.ROTATION_270:
//QtCreator             case Surface.ROTATION_90:
//QtCreator                 return 1;
//QtCreator
//QtCreator             case Surface.ROTATION_0:
//QtCreator             case Surface.ROTATION_180:
//QtCreator                 return 2;
//QtCreator
//QtCreator             default:
//@ANDROID-8
                return -1;
//@ANDROID-8
//QtCreator         }
//@ANDROID-8
    }

    public int backLightStatus()
    {
        int backLight=0;
        try {
            backLight = Settings.System.getInt(QtApplication.mainActivity().getContentResolver(),Settings.System.SCREEN_BRIGHTNESS);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        if((backLight<=BRIGHTNESS_ON) && (backLight>=BRIGHTNESS_DIM))
        {
            return 2;
        }
        else if((backLight>=BRIGHTNESS_OFF) && (backLight<=BRIGHTNESS_DIM))
        {
            return 1;
        }
        else if(backLight==BRIGHTNESS_OFF)
        {
            return 0;
        }
        else
        {
            return -1;
        }

    }

    public int displayBrightness ()
    {
        int backLight=0;
        try {
            backLight = Settings.System.getInt(QtApplication.mainActivity().getContentResolver(),Settings.System.SCREEN_BRIGHTNESS);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        backLight=(backLight*100)/BRIGHTNESS_ON;
        return backLight;
    }

    public float colorDepth ()
    {
        return m_displaymatrics.density;
    }
    //systeminfo
    public void initSystemGeneralInfo()
    {
        createGeneralSystemInfo ();
//@ANDROID-5
//QtCreator         QtApplication.mainActivity().registerReceiver(m_generalSystemInfo,new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
//@ANDROID-5
    }

    public void exitSystemGeneralInfo ()
    {
        try
        {
            QtApplication.mainActivity().unregisterReceiver(m_generalSystemInfo);
        }
        catch(Exception e)
        {

        }
    }

    public void createGeneralSystemInfo ()
    {
        m_generalSystemInfo=new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent)
            {
                    String language=currentLanguage();
                    languageChanged(language);
            }
        };
    }
    public String[] availableLanguages ()
    {
        Locale[] locales=Locale.getAvailableLocales();
        String[] availableLanguages =new String[locales.length];
        for(int langCounter=0;langCounter<locales.length;langCounter ++)
        {
            availableLanguages [langCounter]=locales[langCounter].getDisplayName();
        }
        return availableLanguages;
    }

    public String currentCountryCode ()
    {
        Locale locale= Locale.getDefault();
        return locale.getISO3Country();
    }
    public String currentLanguage ()
    {
        Locale locale= Locale.getDefault();
        return locale.getDisplayName();
    }

    public int[] featuresAvailable()
    {
        int[] features=new int[14];
//@ANDROID-5
//QtCreator         PackageManager pm=QtApplication.mainActivity().getPackageManager();
//QtCreator         if(pm.hasSystemFeature(PackageManager.FEATURE_CAMERA))
//QtCreator         {
//QtCreator             features[1]=1;
//QtCreator         }
//@ANDROID-5
//@ANDROID-8
//QtCreator         if(pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH))
//QtCreator         {
//QtCreator             features[0]=0;
//QtCreator         }
//QtCreator         if((pm.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS))||
//QtCreator                 (pm.hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK)))
//QtCreator         {
//QtCreator             features[2]=10;
//QtCreator         }
//QtCreator         if(pm.hasSystemFeature(PackageManager.FEATURE_WIFI))
//QtCreator         {
//QtCreator             features[7]=8;
//QtCreator         }
//@ANDROID-8
        if(sdcardFeatureAvailable ())
        {
            features[3]=5;
        }
        if(UsbFeature ())
        {
            features[4]=6;
        }
        if(VibFeature ())
        {
            features[5]=7;
            features[6]=12;
        }
        if(m_telephonyManager.getPhoneType()!=TelephonyManager.PHONE_TYPE_NONE)
        {
            features[8]=9;
        }
        return features;
    }

    private boolean sdcardFeatureAvailable ()
    {
            File dir = new File("/sys/class");
            String list="";

            String[] children = dir.list();
            if (children == null) {
                return false;
            }
            else {
                for (int i=0; i<children.length; i++) {
                    list += children[i];
                }
            }
            list=list.trim();
            if((-1!=list.toLowerCase().indexOf("mmc")))
            {
                    return true;
            }
            return false;
    }

    private boolean UsbFeature ()
    {
        File dir = new File("/sys/class");
        String list="";

        String[] children = dir.list();
        if (children == null) {
            return false;
        }
        else {
            for (int i=0; i<children.length; i++) {
                list += children[i];
            }
        }
        list=list.trim();
        if((-1!=list.toLowerCase().indexOf("usb")))
        {
                return true;
        }
        return false;
    }

    private boolean VibFeature ()
    {
        File dir = new File("/sys/class/timed_output/vibrator/enable");
        if(dir.exists())
        {
            return true;
        }
        return false;
    }

    //storage
    public void initStorage ()
    {
        createStorageInfoBroadcastReceiver ();
        QtApplication.mainActivity().registerReceiver(m_storageInfoBroadcastReceiver,new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW));
        QtApplication.mainActivity().registerReceiver(m_storageInfoBroadcastReceiver,new IntentFilter(Intent.ACTION_DEVICE_STORAGE_OK));
        IntentFilter mediaFilter=new IntentFilter(Intent.ACTION_MEDIA_SHARED);
        mediaFilter.addAction(Intent.ACTION_MEDIA_EJECT);
        mediaFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        mediaFilter.addAction(Intent.ACTION_MEDIA_NOFS);
        mediaFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
        mediaFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
        mediaFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        QtApplication.mainActivity().registerReceiver(m_storageInfoBroadcastReceiver,mediaFilter);
    }

    public void exitStorage ()
    {
        try
        {
            QtApplication.mainActivity().unregisterReceiver(m_storageInfoBroadcastReceiver);
        }
        catch(Exception e)
        {

        }
    }

    private void createStorageInfoBroadcastReceiver ()
    {
        m_storageInfoBroadcastReceiver=new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                if((intent.getAction().equals(Intent.ACTION_DEVICE_STORAGE_LOW)))
                {
                    storageStateChanged();
                }
                else if((intent.getAction().equals(Intent.ACTION_DEVICE_STORAGE_OK)))
                {
                    storageStateChanged();
                }
                else if( (intent.getAction().equals(Intent.ACTION_MEDIA_SHARED)) ||
                    (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) ||
                    (intent.getAction().equals(Intent.ACTION_MEDIA_NOFS)) )

                {
                    Uri mountPath=intent.getData();
                    logicalDriveChanged(mountPath.getEncodedPath(),true);
                }
                else if ((intent.getAction().equals(Intent.ACTION_MEDIA_REMOVED)) ||
                    (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTABLE)) ||
                    (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)) )
                {
                    Uri mountPath=intent.getData();
                    logicalDriveChanged(mountPath.getEncodedPath(),false);
                }
            }
        };
    }
    //network
    public void initNetwork ()
    {
        m_connectivityManager=(ConnectivityManager)QtApplication.mainActivity().
                                                            getSystemService(Context.CONNECTIVITY_SERVICE);
        m_wifiManager=(WifiManager)QtApplication.mainActivity().getSystemService(Context.WIFI_SERVICE);

        QtApplication.mainActivity().runOnUiThread(new Runnable() {

            public void run()
            {
                m_phoneStateListener=new PhoneStateListener()
                {
                    @Override
                    public void  onCellLocationChanged  (CellLocation location)
                    {
                        if(m_telephonyManager.getPhoneType()==TelephonyManager.PHONE_TYPE_GSM)
                        {
                            GsmCellLocation gsmCellLocation=(GsmCellLocation)location;
                            int cellId=gsmCellLocation.getCid();
                            QtSystemInfo.cellIdChanged(cellId);
                        }
                    }

//@ANDROID-5
//QtCreator                     @Override
//QtCreator                     public void  onSignalStrengthsChanged (SignalStrength signalStrength)
//QtCreator                     {
//QtCreator                         int strength=0;
//QtCreator                         if(signalStrength.isGsm())
//QtCreator                         {
//QtCreator                             strength=signalStrength.getGsmSignalStrength();
//QtCreator                             strength=(strength*100)/30;
//QtCreator                             if(strength>100)
//QtCreator                             {
//QtCreator                                 strength=0;
//QtCreator                             }
//QtCreator                         }
//QtCreator                         QtSystemInfo.phoneSignalStrengthChanged(strength);
//QtCreator                     }
//@ANDROID-5

                    @Override
                    public void  onServiceStateChanged  (ServiceState serviceState)
                    {
                        int state=0;
                        int networkmode=1;
                        if( (m_telephonyManager.isNetworkRoaming()) )
                        {
                            state=8;
                        }
                        else if(serviceState.getState()==ServiceState.STATE_EMERGENCY_ONLY)
                        {
                            state= 2;
                        }
                        else if(serviceState.getState()==ServiceState.STATE_OUT_OF_SERVICE)
                        {
                            state=1;
                        }
                        else if(serviceState.getState()==ServiceState.STATE_IN_SERVICE)
                        {
                            state=5;
                        }
                        else if(serviceState.getState()==ServiceState.STATE_POWER_OFF)
                        {
                            state=0;
                        }
                        if(m_telephonyManager.getPhoneType()==TelephonyManager.PHONE_TYPE_GSM)
                        {
                            networkmode=1;
                        }
                        else if(m_telephonyManager.getPhoneType()==TelephonyManager.PHONE_TYPE_CDMA)
                        {
                            networkmode=2;
                        }
                        String networkName="";
                        networkName=m_telephonyManager.getSimOperator();
                        QtSystemInfo.serviceStatusChanged(state,networkmode);
                        QtSystemInfo.networkNameChanged(networkmode, networkName);
                    }

//@ANDROID-5
//QtCreator                     @Override
//QtCreator                     public void  onDataConnectionStateChanged  (int state, int networkType)
//QtCreator                     {
//QtCreator                         switch(networkType)
//QtCreator                         {
//QtCreator                             case TelephonyManager.NETWORK_TYPE_EDGE:
//QtCreator                                     networkType=9;
//QtCreator                                     break;
//QtCreator                             case TelephonyManager.NETWORK_TYPE_GPRS:
//QtCreator                                     networkType=8;
//QtCreator                                     break;
//QtCreator                             case TelephonyManager.NETWORK_TYPE_HSPA:
//QtCreator                                     networkType=10;
//QtCreator                                     break;
//QtCreator                             default:
//QtCreator                                     networkType=0;
//QtCreator                         }
//QtCreator                         switch(state)
//QtCreator                         {
//QtCreator                             case TelephonyManager.DATA_CONNECTED:
//QtCreator                                     state=5;
//QtCreator                                     break;
//QtCreator                             case TelephonyManager.DATA_DISCONNECTED:
//QtCreator                                     state=1;
//QtCreator                                     break;
//QtCreator                             case TelephonyManager.DATA_SUSPENDED:
//QtCreator                                     state=7;
//QtCreator                                     break;
//QtCreator                             case TelephonyManager.DATA_CONNECTING:
//QtCreator                                     state=3;
//QtCreator                                     break;
//QtCreator                             default:
//QtCreator                                     state=0;
//QtCreator                                     break;
//QtCreator                         }
//QtCreator
//QtCreator                         QtSystemInfo.networkStatusChanged(state, networkType);
//QtCreator                     }
//@ANDROID-5
                };

            }
        });
        createWifiBroadcastReceiver();
        QtApplication.mainActivity().registerReceiver(m_networkBroadcastReceiver,new IntentFilter(WifiManager.RSSI_CHANGED_ACTION));
        QtApplication.mainActivity().registerReceiver(m_networkBroadcastReceiver,new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
        QtApplication.mainActivity().registerReceiver(m_networkBroadcastReceiver,new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
        int events=
//@ANDROID-5
//QtCreator             PhoneStateListener.LISTEN_SIGNAL_STRENGTHS|
//@ANDROID-5
            PhoneStateListener.LISTEN_SERVICE_STATE
                |PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
                |PhoneStateListener.LISTEN_CELL_LOCATION;
        m_telephonyManager.listen(m_phoneStateListener,events);
    }

    public void exitNetwork ()
    {
        QtApplication.mainActivity().unregisterReceiver(m_networkBroadcastReceiver);
        m_telephonyManager.listen(m_phoneStateListener, 0);
    }

    private void  createWifiBroadcastReceiver ()
    {
        m_networkBroadcastReceiver=new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent)
            {
                if((intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)))
                {
                    int strength=intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, 0);
                    strength=255+strength;
                    strength=(strength*100)/255;
                    wifiSignalStrengthChanged(strength);
                }
                else if((intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)))
                {
                    String name="";
                    NetworkInfo networkInfo=intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    int status=WifiStatus(networkInfo.getDetailedState());
                    wifiStatusChanged(status);
                    WifiInfo info=m_wifiManager.getConnectionInfo();
                    if(m_wifiManager.getWifiState()!=WifiManager.WIFI_STATE_DISABLED)
                    {
                        name=info.getSSID();
                    }
                    networkNameChanged(4, name);
                }
                else if((intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)))
                {
                    String name="";
                    int wifiState=intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                    if(WifiManager.WIFI_STATE_DISABLED==wifiState)
                    {
                        wifiStatusChanged(wifiState);
                        name=" ";
                        networkNameChanged(4, name);
                        wifiSignalStrengthChanged(0);
                    }

                }
            }
        };
    }
    String networkName (int mode)
    {
        String networkName="";
        switch(mode)
        {
        case 1:
            if(m_telephonyManager.getPhoneType()==TelephonyManager.PHONE_TYPE_GSM)
            {
                networkName=m_telephonyManager.getNetworkOperatorName();
            }
            break;
        case 2:
            if(m_telephonyManager.getPhoneType()==TelephonyManager.PHONE_TYPE_CDMA)
            {
                networkName=m_telephonyManager.getNetworkOperatorName();
            }
            break;
        case 3:
            networkName="";
            break;
        case 4:
            int wifiState=m_wifiManager.getWifiState();
            if(wifiState!=WifiManager.WIFI_STATE_DISABLED)
            {
                WifiInfo info=m_wifiManager.getConnectionInfo();
                networkName=info.getSSID();
            }
            break;
        case 5:
            networkName="";
            break;
//@ANDROID-5
//QtCreator         case 6:
//QtCreator             networkName=m_bluetoothAdapter.getName();
//QtCreator             break;
//@ANDROID-5
        case 7:
            break;
        case 8:
            if(m_telephonyManager.getNetworkType()==TelephonyManager.NETWORK_TYPE_GPRS)
            {
                networkName=m_telephonyManager.getNetworkOperatorName();
            }
            break;
        case 9:
            if(m_telephonyManager.getNetworkType()==TelephonyManager.NETWORK_TYPE_EDGE)
            {
                networkName=m_telephonyManager.getNetworkOperatorName();
            }
            break;
//@ANDROID-5
//QtCreator         case 10:
//QtCreator             if(m_telephonyManager.getNetworkType()==TelephonyManager.NETWORK_TYPE_HSPA)
//QtCreator             {
//QtCreator                 networkName=m_telephonyManager.getNetworkOperatorName();
//QtCreator             }
//QtCreator             break;
//@ANDROID-5
        default:
            networkName="";
        }
        return networkName;
    }

    public String macAddress (int mode)
    {
        if(mode==4)
        {
            WifiInfo info=m_wifiManager.getConnectionInfo();
            return info.getMacAddress();
        }
        else
        {
            return "";
        }
    }

    public int bluetoothStatus()
    {
//@ANDROID-5
//QtCreator         if(m_bluetoothAdapter.isDiscovering())
//QtCreator         {
//QtCreator             return 3;
//QtCreator         }
//QtCreator         else if(bluetoothPowerState())
//QtCreator         {
//QtCreator             return 5;
//QtCreator         }
//QtCreator         else
//@ANDROID-5
        {
            return 0;
        }
    }
    public int wifiStatus ()
    {
            NetworkInfo networkInfo=m_connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo.DetailedState state=networkInfo.getDetailedState();
            return WifiStatus (state);
    }

    private int WifiStatus (NetworkInfo.DetailedState state)
    {
        int getState=0;

        if(state==NetworkInfo.DetailedState.CONNECTED)
        {
            getState=5;
        }

        else if(state==NetworkInfo.DetailedState.CONNECTING)
        {
            getState=3;
        }

        else if(state==NetworkInfo.DetailedState.DISCONNECTED)
        {
            getState=1;
        }
        else if(state==NetworkInfo.DetailedState.DISCONNECTING)
        {
            getState=0;
        }
        else if(state== NetworkInfo.DetailedState.FAILED)
        {
            getState=0;
        }
        else if(state== NetworkInfo.DetailedState.IDLE)
        {
            getState=0;
        }
        else if(state==NetworkInfo.DetailedState.SCANNING)
        {
            getState=3;
        }
        else if(state==NetworkInfo.DetailedState.SUSPENDED)
        {
            getState=7;
        }
        return getState;
    }
    public int wifiStrength ()
    {
        WifiInfo info=m_wifiManager.getConnectionInfo();
        int strength=info.getRssi();
        strength=255+strength;
        strength=(strength*100)/255;
        return strength;
    }

    public int cellId ()
    {
        GsmCellLocation gsmLocation = (GsmCellLocation)m_telephonyManager.getCellLocation();
        return gsmLocation.getCid();
    }

    public String currentMobileCountryCode ()
    {
        return m_telephonyManager.getNetworkCountryIso();
    }

    public String currentMobileNetworkCode ()
    {
        String MNC=m_telephonyManager.getSimOperator();
        return MNC;
    }

    public int currentMode ()
    {
//@ANDROID-5
//QtCreator     PackageManager pm=QtApplication.mainActivity().getPackageManager();
//@ANDROID-5
        if(m_telephonyManager.getPhoneType()==TelephonyManager.PHONE_TYPE_GSM)
        {
            return 1;
        }
        else if (m_telephonyManager.getPhoneType()==TelephonyManager.PHONE_TYPE_CDMA)
        {
            return 2;
        }
//@ANDROID-8
//QtCreator         else if (pm.hasSystemFeature(PackageManager.FEATURE_WIFI))
//QtCreator         {
//QtCreator             return 4;
//QtCreator         }
//@ANDROID-8
        else
        {
            return 0;
        }
    }

    public int locationAreaCode ()
    {
        GsmCellLocation gsmLocation = (GsmCellLocation)m_telephonyManager.getCellLocation();
        return gsmLocation.getLac();
    }

    public static native void BatteryDataUpdated(Object batteryInfo);
    //device
    public static native void bluetoothStateChanged(boolean state);
    public static native void profileChanged(int mode);
    public static native void deviceLocked (boolean deviceLocked);
    //system info
    public static native void languageChanged(String language);
    //storage info
    public static native void storageStateChanged();
    public static native void logicalDriveChanged (String mountPath,boolean added);
    //network info
    public static native void phoneSignalStrengthChanged(int strength);
    public static native void wifiSignalStrengthChanged(int strength);
    public static native void serviceStatusChanged (int status,int networkmode);
    public static native void networkStatusChanged (int status,int networkmode);
    public static native void wifiStatusChanged (int status);
    public static native void networkNameChanged(int mode,String name);
    public static native void cellIdChanged (int cellId);
}


code:
<RCC>
    <qresource prefix="/qml">
        <file>core/</file>
        <file>android/</file>
    </qresource>
</RCC>


code:
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Components project.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

// The Page item is intended for use as a root item in QML items that make
// up pages to use with the PageStack.

import QtQuick 1.0
import com.ubuntu.summit.android 1.0

Item {
    id: root

    visible: false

    // Note we do not use anchor fill here because it will force us to relayout
    // hidden children when rotating the screen as well
    width: visible && parent ? parent.width - anchors.leftMargin - anchors.rightMargin : __prevWidth
    height: visible && parent ? parent.height  - anchors.topMargin - anchors.bottomMargin : __prevHeight
    x: parent ? anchors.leftMargin : 0
    y: parent ? anchors.topMargin : 0
    // The status of the page. One of the following:
    //      PageStatus.Inactive - the page is not visible
    //      PageStatus.Activating - the page is transitioning into becoming the active page
    //      PageStatus.Active - the page is the current active page
    //      PageStatus.Deactivating - the page is transitioning into becoming inactive
//    property int status: PageStatus.Inactive

    onWidthChanged: __prevWidth = visible ? width : __prevWidth
    onHeightChanged: __prevHeight = visible ? height : __prevHeight

    property int __prevWidth: 0
    property int __prevHeight: 0

    property bool __isPage: true

    anchors.margins: 0 // Page margins should generally be 16 pixels as defined by UI.MARGIN_XLARGE

    // The status of the page. One of the following:
    //      PageStatus.Inactive - the page is not visible
    //      PageStatus.Activating - the page is transitioning into becoming the active page
    //      PageStatus.Active - the page is the current active page
    //      PageStatus.Deactivating - the page is transitioning into becoming inactive
    property int status: PageStatus.Inactive

    // Defines the tools for the page; null for none.
    property Item tools: null

    // The page stack that the page is in.
    property PageStack pageStack

//    // Defines orientation lock for a page
//    property int orientationLock: PageOrientation.Automatic

//    onStatusChanged: {
//        if (status == PageStatus.Activating) {
//            __updateOrientationLock()
//        }
//    }

//    onOrientationLockChanged: {
//        __updateOrientationLock()
//    }

//    function __updateOrientationLock() {
//        switch (orientationLock) {
//        case PageOrientation.Automatic:
//            screen.setAllowedOrientations(Screen.Portrait | Screen.Landscape);
//            break
//        case PageOrientation.LockPortrait:
//            screen.setAllowedOrientations(Screen.Portrait);
//            break
//        case PageOrientation.LockLandscape:
//            screen.setAllowedOrientations(Screen.Landscape);
//            break
//        case PageOrientation.LockPrevious:
//            // Allowed orientation should be changed to current
//            // if previously it was locked, it will remain locked
//            // if previously it was not locked, it will be locked to current
//            screen.setAllowedOrientations(screen.currentOrientation);
//            break
//        }
//    }
}


code:
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Components project.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

// Page stack. Items are page containers.
var pageStack = [];

// Page component cache map. Key is page url, value is page component.
var componentCache = {};

// Returns the page stack depth.
function getDepth() {
    return pageStack.length;
}

// Pushes a page on the stack.
function push(page, properties, replace, immediate) {
    // page order sanity check
    if ((!replace && page == currentPage) ||
            (replace && pageStack.length > 1 && page == pageStack[pageStack.length - 2].page)) {
        throw new Error("Cannot navigate so that the resulting page stack has two consecutive entries of the same page instance.");
    }

    // figure out if more than one page is being pushed
    var pages;
    if (page instanceof Array) {
        pages = page;
        page = pages.pop();
        if (page.createObject === undefined && page.parent === undefined && typeof page != "string") {
            properties = properties || page.properties;
            page = page.page;
        }
    }

    // get the current container
    var oldContainer = pageStack[pageStack.length - 1];

    // pop the old container off the stack if this is a replace
    if (oldContainer && replace) {
        pageStack.pop();
    }

    // push any extra defined pages onto the stack
    if (pages) {
        var i;
        for (i = 0; i < pages.length; i++) {
            var tPage = pages[i];
            var tProps;
            if (tPage.createObject === undefined && tPage.parent === undefined && typeof tPage != "string") {
                tProps = tPage.properties;
                tPage = tPage.page;
            }
            pageStack.push(initPage(tPage, tProps));
        }
    }

    // initialize the page
    var container = initPage(page, properties);

    // push the page container onto the stack
    pageStack.push(container);

    depth = pageStack.length;
    currentPage = container.page;

    // perform page transition
    immediate = immediate || !oldContainer;
    if (oldContainer) {
        oldContainer.pushExit(replace, immediate);
    }
    container.pushEnter(replace, immediate);

    return container.page;
}

// Initializes a page and its container.
function initPage(page, properties) {
    var container = containerComponent.createObject(root);

    var pageComp;
    if (page.createObject) {
        // page defined as component
        pageComp = page;
    } else if (typeof page == "string") {
        // page defined as string (a url)
        pageComp = componentCache[page];
        if (!pageComp) {
            pageComp = componentCache[page] = Qt.createComponent(page);
        }
    }
    if (pageComp) {
        if (pageComp.status == Component.Error) {
            throw new Error("Error while loading page: " + pageComp.errorString());
        } else {
            // instantiate page from component
            page = pageComp.createObject(container, properties || {});
        }
    } else {
        // copy properties to the page
        for (var prop in properties) {
            if (properties.hasOwnProperty(prop)) {
                page[prop] = properties[prop];
            }
        }
    }

    container.page = page;
    container.owner = page.parent;

    // the page has to be reparented if
    if (page.parent != container) {
        page.parent = container;
    }

    if (page.pageStack !== undefined) {
        page.pageStack = root;
    }

    return container;
}

// Pops a page off the stack.
function pop(page, immediate) {
    // make sure there are enough pages in the stack to pop
    if (pageStack.length > 1) {
        // pop the current container off the stack and get the next container
        var oldContainer = pageStack.pop();
        var container = pageStack[pageStack.length - 1];
        if (page !== undefined) {
            // an unwind target has been specified - pop until we find it
            while (page != container.page && pageStack.length > 1) {
                container.cleanup();
                pageStack.pop();
                container = pageStack[pageStack.length - 1];
            }
        }

        depth = pageStack.length;
        currentPage = container.page;

        // perform page transition
        oldContainer.popExit(immediate);
        container.popEnter(immediate);

        return oldContainer.page;
    } else {
        return null;
    }
}

// Clears the page stack.
function clear() {
    var container;
    while (container = pageStack.pop()) {
        container.cleanup();
    }
    depth = 0;
    currentPage = null;
}

// Iterates through all pages in the stack (top to bottom) to find a page.
function find(func) {
    for (var i = pageStack.length - 1; i >= 0; i--) {
        var page = pageStack[i].page;
        if (func(page)) {
            return page;
        }
    }
    return null;
}


code:
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Components project.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

// The PageStack item defines a container for pages and a stack-based
// navigation model. Pages can be defined as QML items or components.

import QtQuick 1.0
import com.ubuntu.summit.android 1.0
import "PageStack.js" as Engine

Item {
    id: root

    width: parent ? parent.width : 0
    height: parent ? parent.height : 0

    // Page stack depth.
    property int depth: Engine.getDepth()

    // The currently active page.
    property Item currentPage: null

    // Indicates whether there is an ongoing page transition.
    property bool busy: __ongoingTransitionCount > 0

    // The number of ongoing transitions.
    property int __ongoingTransitionCount: 0

    // Pushes a page on the stack.
    // The page can be defined as a component, item or string.
    // If an item is used then the page will get re-parented.
    // If a string is used then it is interpreted as a url that is used to load a page component.
    //
    // The page can also be given as an array of pages. In this case all those pages will be pushed
    // onto the stack. The items in the stack can be components, items or strings just like for single
    // pages. Additionally an object can be used, which specifies a page and an optional properties
    // property. This can be used to push multiple pages while still giving each of them properties.
    // When an array is used the transition animation will only be to the last page.
    //
    // The properties argument is optional and allows defining a map of properties to set on the page.
    // If the immediate argument is true then no transition animation is performed.
    // Returns the page instance.
    function push(page, properties, immediate) {
        return Engine.push(page, properties, false, immediate);
    }

    // Pops a page off the stack.
    // If page is specified then the stack is unwound to that page; null to unwind the to first page.
    // If the immediate argument is true then no transition animation is performed.
    // Returns the page instance that was popped off the stack.
    function pop(page, immediate) {
        return Engine.pop(page, immediate);
    }

    // Replaces a page on the stack.
    // See push() for details.
    function replace(page, properties, immediate) {
        return Engine.push(page, properties, true, immediate);
    }

    // Clears the page stack.
    function clear() {
        return Engine.clear();
    }

    // Iterates through all pages (top to bottom) and invokes the specified function.
    // If the specified function returns true the search stops and the find function
    // returns the page that the iteration stopped at. If the search doesn't result
    // in any page being found then null is returned.
    function find(func) {
        return Engine.find(func);
    }

    // Called when the page stack visibility changes.
    onVisibleChanged: {
        if (currentPage) {
            __setPageStatus(currentPage, visible ? PageStatus.Active : PageStatus.Inactive);
            if (visible) {
                currentPage.visible = currentPage.parent.visible = true;
            }
        }
    }

    // Sets the page status.
    function __setPageStatus(page, status) {
        if (page.status !== undefined) {
            if (status == PageStatus.Active && page.status == PageStatus.Inactive) {
                page.status = PageStatus.Activating;
            } else if (status == PageStatus.Inactive && page.status == PageStatus.Active) {
                page.status = PageStatus.Deactivating;
            }
            page.status = status;
        }
    }

    // Component for page containers.
    Component {
        id: containerComponent

        Item {
            id: container

            width: parent ? parent.width : 0
            height: parent ? parent.height : 0

            // The states correspond to the different possible positions of the container.
            state: "hidden"

            // The page held by this container.
            property Item page: null

            // The owner of the page.
            property Item owner: null

            // Duration of transition animation (in ms)
            property int transitionDuration: 500

            // Flag that indicates the container should be cleaned up after the transition has ended.
            property bool cleanupAfterTransition: false

            // Performs a push enter transition.
            function pushEnter(replace, immediate) {
                if (!immediate) {
                    state = replace ? "front" : "right";
                }
                state = "";
                page.visible = true;
                if (root.visible && immediate) {
                    __setPageStatus(page, PageStatus.Active);
                }
            }

            // Performs a push exit transition.
            function pushExit(replace, immediate) {
                state = immediate ? "hidden" : (replace ? "back" : "left");
                if (root.visible && immediate) {
                    __setPageStatus(page, PageStatus.Inactive);
                }
                if (replace) {
                    if (immediate) {
                        cleanup();
                    } else {
                        cleanupAfterTransition = true;
                    }
                }
            }

            // Performs a pop enter transition.
            function popEnter(immediate) {
                if (!immediate) {
                    state = "left";
                }
                state = "";
                page.visible = true;
                if (root.visible && immediate) {
                    __setPageStatus(page, PageStatus.Active);
                }
            }

            // Performs a pop exit transition.
            function popExit(immediate) {
                state = immediate ? "hidden" : "right";
                if (root.visible && immediate) {
                    __setPageStatus(page, PageStatus.Inactive);
                }
                if (immediate) {
                    cleanup();
                } else {
                    cleanupAfterTransition = true;
                }
            }

            // Called when a transition has started.
            function transitionStarted() {
                __ongoingTransitionCount++;
                if (root.visible) {
                    __setPageStatus(page, (state == "") ? PageStatus.Activating : PageStatus.Deactivating);
                }
            }

            // Called when a transition has ended.
            function transitionEnded() {
                if (state != "") {
                    state = "hidden";
                }
                if (root.visible) {
                    __setPageStatus(page, (state == "") ? PageStatus.Active : PageStatus.Inactive);
                }
                __ongoingTransitionCount--;
                if (cleanupAfterTransition) {
                    cleanup();
                }
            }

            states: [
                // Explicit properties for default state.
                State {
                    name: ""
                    PropertyChanges { target: container; visible: true }
                },
                // Start state for pop entry, end state for push exit.
                State {
                    name: "left"
                    PropertyChanges { target: container; x: -width }
                },
                // Start state for push entry, end state for pop exit.
                State {
                    name: "right"
                    PropertyChanges { target: container; x: width }
                },
                // Start state for replace entry.
                State {
                    name: "front"
                    PropertyChanges { target: container; scale: 1.5; opacity: 0.0 }
                },
                // End state for replace exit.
                State {
                    name: "back"
                    PropertyChanges { target: container; scale: 0.5; opacity: 0.0 }
                },
                // Inactive state.
                State {
                    name: "hidden"
                    PropertyChanges { target: container; visible: false }
                }
            ]

            transitions: [
                // Pop entry and push exit transition.
                Transition {
                    from: ""; to: "left"; reversible: true
                    SequentialAnimation {
                        ScriptAction { script: if (state == "left") { transitionStarted(); } else { transitionEnded(); } }
                        PropertyAnimation { properties: "x"; easing.type: Easing.InOutExpo; duration: transitionDuration }
                        ScriptAction { script: if (state == "left") { transitionEnded(); } else { transitionStarted(); } }
                    }
                },
                // Push entry and pop exit transition.
                Transition {
                    from: ""; to: "right"; reversible: true
                    SequentialAnimation {
                        ScriptAction { script: if (state == "right") { transitionStarted(); } else { transitionEnded(); } }
                        PropertyAnimation { properties: "x"; easing.type: Easing.InOutExpo; duration: transitionDuration }
                        ScriptAction { script: if (state == "right") { transitionEnded(); } else { transitionStarted(); } }
                    }
                },
                // Replace entry transition.
                Transition {
                    from: "front"; to: "";
                    SequentialAnimation {
                        ScriptAction { script: transitionStarted(); }
                        PropertyAnimation { properties: "scale,opacity"; easing.type: Easing.InOutExpo; duration: transitionDuration }
                        ScriptAction { script: transitionEnded(); }
                    }
                },
                // Replace exit transition.
                Transition {
                    from: ""; to: "back";
                    SequentialAnimation {
                        ScriptAction { script: transitionStarted(); }
                        PropertyAnimation { properties: "scale,opacity"; easing.type: Easing.InOutExpo; duration: transitionDuration }
                        ScriptAction { script: transitionEnded(); }
                   }
                }
            ]

            // Cleans up the container and then destroys it.
            function cleanup() {
                if (page.status == PageStatus.Active) {
                    __setPageStatus(page, PageStatus.Inactive);
                }
                if (owner != container) {
                    // container is not the owner of the page - re-parent back to original owner
                    page.visible = false;
                    page.parent = owner;
                }
                container.destroy();
            }

        }
    }

}


code:
import QtQuick 1.0

Item {
    id: window

    property alias pageStack: stack

    PageStack {
        id: stack
        anchors.fill: parent
    }
}


code:
/*
    Copyright (C) 2011 Harald Sitter <apachelogger@ubuntu.com>

    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 <http://www.gnu.org/licenses/>.
*/

import QtQuick 1.0

PageStackWindow {
    id: window

    Page {
        id: pp
        Rectangle {
            anchors.fill: parent
            color: "orange"
        }
        Rectangle { anchors.centerIn: parent; width: 100; height: 100; color: "green"
            MouseArea {anchors.fill: parent; onClicked: pageStack.push(dd) }
        }
    }

    Page {
        id: dd
        Rectangle {
            anchors.fill: parent
            color: "green"
        }
        Rectangle { anchors.centerIn: parent; width: 100; height: 100; color: "blue"
            MouseArea {anchors.fill: parent; onClicked: pageStack.push(aa) }
        }
    }

    Page {
        id: aa
        Rectangle {
            anchors.fill: parent
            color: "blue"
        }
        Rectangle { anchors.centerIn: parent; width: 100; height: 100; color: "red"
            MouseArea {anchors.fill: parent; onClicked: pageStack.push(bb) }
        }
    }

    Page {
        id: bb
        Rectangle {
            anchors.fill: parent
            color: "red"
        }
        Rectangle { anchors.centerIn: parent; width: 100; height: 100; color: "yellow"
            MouseArea {anchors.fill: parent; onClicked: pageStack.push(cc) }
        }
    }

    Page {
        id: cc
        Rectangle {
            anchors.fill: parent
            color: "yellow"
        }
    }

    Keys.onPressed: {
        if (event.key == Qt.Key_TopMenu)
            console.debug("QML: opening menu!")
        else if (event.key == Qt.Key_Close) {
            console.debug("QML: closing! (maybe)")
            pageStack.depth <= 1 ? Qt.quit() : pageStack.pop()
        }
    }

    anchors.fill: parent
    focus: true

    Component.onCompleted: {
        pageStack.push(pp)
        pageStack.push(dd)
        pageStack.push(aa)
        pageStack.push(bb)
        pageStack.push(cc)
    }
}


code:
/*
    Copyright (C) 2011 Harald Sitter <apachelogger@ubuntu.com>

    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 <http://www.gnu.org/licenses/>.
*/

import QtQuick 1.0

ListModel {
    ListElement {
        year: "2011"
        name: "Harald Sitter"
        mail: "apachelogger@ubuntu.com"
    }
    ListElement {
        year: "2011"
        name: "Rohan Garg"
        mail: "rohangarg@ubuntu.com"
    }
}


code:
import QtQuick 1.0
import "../core/weekday.js" as WeekDay

ListModel {
    id: model

    Component.onCompleted: {
        for (var i = 0; i < WeekDay.weekday.length; ++i) {
            if (i == 0 || i == 6)
                continue;
            model.append({"name": WeekDay.numberToString(i), "number": i})
        }
    }
}


code:
/*
    Copyright (C) 2011 Harald Sitter <apachelogger@ubuntu.com>

    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 <http://www.gnu.org/licenses/>.
*/

import QtQuick 1.0

QtObject {
    property ListModel listModel: ListModel {}
    signal listModelChanged

    function load(url) {
        listModel.clear();
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true)
        xhr.onreadystatechange = function() {
            if (xhr.readyState == xhr.DONE) {
//                if (xhr.status == 200) {
                    __loaded(JSON.parse(xhr.responseText))
//                }
            }
        }
        xhr.send();
    }

    function __loaded(jsonArray) {
        for (var i = 0; i < jsonArray.length; ++i) {
            listModel.append(jsonArray[i]);
        }
        listModelChanged()
    }
}


code:
/*
    Copyright (C) 2011 Harald Sitter <apachelogger@ubuntu.com>

    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 <http://www.gnu.org/licenses/>.
*/

import com.ubuntu.summit 1.0

Settings {}