#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# We're using PySide, Nokia's official LGPL bindings.
# You can however easily use PyQt (Riverside Computing's GPL bindings) by commenting these and fixing the appropriate imports.
import sys, os, time, thread
import glib, gobject
import pygst
pygst.require("0.10")
import gst
from ctypes import *
import subprocess
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtMaemo5 import QMaemo5ValueButton, QMaemo5InformationBox
import dbus.mainloop.qt
import codecs

# In Qt, everything is a class.
# We can subclass stuff to do whatever we want - it seems a bit strange at first,
# but it keeps all related functionality in one place, which helps to keep you organised.
#
# We're subclassing 'QWidget' here. QWidget is the base class for all graphical elements in Qt.
# You can do all sorts of cool things like drawing your widget yourself, but we won't get into that.
#
# See also:
#   http://doc.trolltech.com/4.6/qwidget.html

####################
# Global variables #
####################
CooktimerVersion = "0.0.4-22"
CurrentPreset = 1
Preset1name1 = ""
Preset1name2 = ""
Preset2name1 = ""
Preset2name2 = ""
Preset3name1 = ""
Preset3name2 = ""
ShowPreset1 = True
ShowPreset2 = False
ShowPreset3 = False
temp_ShowPreset = range(0)
temp_Presetname1 = range(0)
temp_Presetname2 = range(0)
temp_Backlight = range(0)
temp_Wakeup = range(0)
temp_Vibration = range(0)
temp_Sound = range(0)
temp_Ledblink = range(0)
temp_Alarmbanner = range(0)
temp_Volume = range(0)
temp_Alarmfile = range(0)
Vibration = False
Sound = False
Wakeup = False
Alarmbanner = False
Backlight = False
Ledblink = False
Volume = 50
defaultVolume = 50
Orientation = "Auto"
Home = os.path.expanduser("~")
CommentChar = '#'
OptionChar =  ' '
Cooktimer_CfgDir = Home + '/.config/cooktimer/'
Cooktimer_CfgFile_legacy = Cooktimer_CfgDir + 'cooktimer.cfg'
Cooktimer_CfgFile = range(4)
for i in range(0,4):
    Cooktimer_CfgFile[i] = Cooktimer_CfgDir + 'cooktimer.cfg' + str(i)
Cooktimer_ItemFile = Cooktimer_CfgDir + 'cooktimer.items'
Cooktimer_StartItems_legacy = Cooktimer_CfgDir + 'cooktimer.start-items'
Cooktimer_Start = Cooktimer_CfgDir + 'cooktimer.start'
Cooktimer_NotesDir = Cooktimer_CfgDir + 'cooktimer.item-notes/'
hoursPicked0 = "00"
minutesPicked0 = "00"
secondsPicked0 = "00"
hoursPicked1 = "00"
minutesPicked1 = "00"
secondsPicked1 = "00"
hoursPicked2 = "00"
minutesPicked2 = "00"
secondsPicked2 = "00"
hoursPicked3 = "00"
minutesPicked3 = "00"
secondsPicked3 = "00"
hoursPicked1saved = ""
minutesPicked1saved = ""
secondsPicked1saved = ""
hoursPicked2saved = ""
minutesPicked2saved = ""
secondsPicked2saved = ""
hoursPicked3saved = ""
minutesPicked3saved = ""
secondsPicked3saved = ""
dishName = ""
dishName1 = ""
dishName1banner = ""
dishPicked1Nbr = ""
dishName2 = ""
dishName2banner = ""
dishPicked2Nbr = ""
dishName3 = ""
dishName3banner = ""
dishPicked3Nbr = ""
rowNbr=1
msgTxtPicked1_1 = ""
msgTimePicked1_1 = ""
msgTxtPicked1_2 = ""
msgTimePicked1_2 = ""
msgTxtPicked1_3 = ""
msgTimePicked1_3 = ""
msgTxtPicked2_1 = ""
msgTimePicked2_1 = ""
msgTxtPicked2_2 = ""
msgTimePicked2_2 = ""
msgTxtPicked2_3 = ""
msgTimePicked2_3 = ""
msgTxtPicked3_1 = ""
msgTimePicked3_1 = ""
msgTxtPicked3_2 = ""
msgTimePicked3_2 = ""
msgTxtPicked3_3 = ""
msgTimePicked3_3 = ""
pause1 = False
pause2 = False
pause3 = False
isStopwatchMode1 = False
isStopwatchMode2 = False
isStopwatchMode3 = False
isContinueMode1 = False
isContinueMode1Active = False
isContinueMode1Restore = False
isContinueMode2 = False
isContinueMode2Active = False
isContinueMode2Restore = False
isContinueMode3 = False
isContinueMode3Active = False
isContinueMode3Restore = False
currSelector = 0
currTimer = 0
playstate = 2
Playbin2 = gst.element_factory_make("playbin2", "player")
Alarmfile = "/opt/cooktimer/alarmsounds/cooktimer.mp3"
hPath = ""

##########################################
# gstreamer stuff to play in silent mode #
# concept by Faheem Pervez               #
##########################################
pulse_lib = CDLL("libpulse-mainloop-glib.so.0")
gobject_lib = CDLL("libgobject-2.0.so.0")

g_object_set = gobject_lib.g_object_set

class PA_PROPLIST(Structure):
  _fields_ = [("_opaque_struct", c_int)]

# pa_proplist_*
pa_proplist_new = pulse_lib.pa_proplist_new
pa_proplist_new.restype = POINTER(PA_PROPLIST)
pa_proplist_new.argtypes = [ ]

pa_proplist_sets = pulse_lib.pa_proplist_sets
pa_proplist_sets.restype = c_int
pa_proplist_sets.argtypes = [
        POINTER(PA_PROPLIST),
        c_char_p,
        c_char_p
]

pa_proplist_free = pulse_lib.pa_proplist_free
pa_proplist_sets.restype = None
pa_proplist_sets.argtypes = [
        POINTER(PA_PROPLIST),
]


def parse_config(self, filename):
    options = {}
    f = codecs.open(filename,"r","utf-8")
    for line in f:
        # First, remove comments:
        if CommentChar in line:
            # split on comment char, keep only the part before
            line, comment = line.split(CommentChar, 1)
        # Second, find lines with an option=value:
        if OptionChar in line:
            # split on option char:
            option, value = line.split(OptionChar, 1)
            # strip spaces:
            option = option.strip()
            value = value.strip()
            # store in dictionary:
            options[option] = value
    f.close()
    return options

def load_dishes(self):
    global OptionChar
    OptionChar = "|"
    cooktimer_items = parse_config(self,Cooktimer_ItemFile)
    DishList = ""
    # make a new list for sorting case-insensitive
    for item in cooktimer_items:
        DishList = DishList + item + '|' + cooktimer_items[item] + "\n"
    contentsList = DishList.split('\n')
    contentsList = contentsList[:-1]
    contentsList.sort(lambda a, b: cmp(a.upper(), b.upper()))
    # initialize array
    dishes = []
    for dish in contentsList:
        item, value  = dish.split(OptionChar,1)
        dishes.append([item,value])
    return dishes

def Alarm(self):
    global playstate
    # display blinking led for 10 seconds
    if Ledblink:
        os.system("(dbus-send --system --type=method_call --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_led_pattern_activate string:PatternError;sleep 10;dbus-send --system --type=method_call --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_led_pattern_deactivate string:PatternError)&")
    if Wakeup:
        # Switch on backlight to be sure message is displayed
        strUnlock = "dbus-send --print-reply --system --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_tklock_mode_change string:unlocked"
        QProcess.startDetached(strUnlock)
    if Vibration:
        os.system('dbus-send --system --print-reply --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_start_manual_vibration int32:250 int32:3000')
    if Sound:
        getVolume(self)
        bus = dbus.SessionBus()
        obj = bus.get_object("com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer",
            "/com/nokia/mafw/renderer/gstrenderer")
        state = dbus.Interface(obj, "com.nokia.mafw.renderer")
        playlist, index, playstate, object_id = state.get_status()
        if playstate == 1:
            # Stopped = 0 Playing = 1 Paused = 2 Transitioning = 3
            os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.pause")
        os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
            com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(Volume))
        # use workaround for silent profile
        mainclass = Gstreamer_play()
        thread.start_new_thread(mainclass.start, ())
        gobject.threads_init()

def printMsg(self,message,duration):
        box = QMaemo5InformationBox()
        box.information(self, message, duration)
        box.show()

def format_seconds_to_hhmmss(seconds):
    hours = seconds // (60*60)
    seconds %= (60*60)
    minutes = seconds // 60
    seconds %= 60
    return "%02i:%02i:%02i" % (hours, minutes, seconds)

def getVolume(self):
    global defaultVolume
    bus = dbus.SessionBus()
    obj = bus.get_object("com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer", "/com/nokia/mafw/renderer/gstrenderer")
    mafw = dbus.Interface(obj, "com.nokia.mafw.extension")
    defaultVolume = int(mafw.get_extension_property("volume")[1])

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):# first things first, we need to initialise the Qt parent, otherwise it won't work properly.
        #
        super(MyMainWindow, self).__init__(parent)
        self.setAttribute(Qt.WA_Maemo5StackedWindow)
        global Orientation
        self.setWindowTitle("cooktimer")

        # catch dbus signal for keyboard slider
        dbus.mainloop.qt.DBusQtMainLoop(set_as_default=True)
        bus = dbus.SystemBus()
        bus.add_signal_receiver(self.handle_slide, path='/org/freedesktop/Hal/devices/platform_slide', dbus_interface='org.freedesktop.Hal.Device', signal_name='PropertyModified')

        # Create config dir if needed
        if not os.path.exists(Cooktimer_CfgDir):
            os.mkdir(Cooktimer_CfgDir)
        # Create config files if needed
        if not os.path.isfile(Cooktimer_CfgFile[0]):
            try:
                newConfigFile = open(Cooktimer_CfgFile[0],"w")
            except:
                QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_CfgFile[0])
            else:
                newConfigFile.write("currentpreset 1\n")
                newConfigFile.write("preset1name1 \n")
                newConfigFile.write("preset1name2 \n")
                newConfigFile.write("preset2name1 \n")
                newConfigFile.write("preset2name2 \n")
                newConfigFile.write("preset3name1 \n")
                newConfigFile.write("preset3name2 \n")
                newConfigFile.write("showpreset2inmenu false\n")
                newConfigFile.write("showpreset3inmenu false\n")
                # Import legacy config file if needed
                if os.path.isfile(Cooktimer_CfgFile_legacy):
                    cooktimer_opts = parse_config(self,Cooktimer_CfgFile_legacy)
                    oldConfigFile = open(Cooktimer_CfgFile_legacy,"r")
                    oldlines = oldConfigFile.readlines()
                    oldConfigFile.close()
                    orientationset = False
                    for line in oldlines:
                        if 'orientation' in line:
                            newConfigFile.write("orientation " + cooktimer_opts["orientation"] + "\n")
                            orientationset = True
                    if not orientationset:
                        newConfigFile.write("orientation auto\n")
                else:
                    newConfigFile.write("orientation auto\n")
                newConfigFile.close()
        else:
            currentpresetset = False
            preset1name1set = False
            preset1name2set = False
            preset2name1set = False
            preset2name2set = False
            preset3name1set = False
            preset3name2set = False
            showpreset2set = False
            showpreset3set = False
            orientationset = False
            ConfigFile = open(Cooktimer_CfgFile[0],"r")
            lines = ConfigFile.readlines()
            for line in lines:
                if 'currentpreset' in line:
                    currentpresetset = True
                if 'preset1name1' in line:
                    preset1name1set = True
                if 'preset1name2' in line:
                    preset1name2set = True
                if 'preset2name1' in line:
                    preset2name1set = True
                if 'preset2name2' in line:
                    preset2name2set = True
                if 'preset3name1' in line:
                    preset3name1set = True
                if 'preset3name2' in line:
                    preset3name2set = True
                if 'showpreset2inmenu' in line:
                    showpreset2set = True
                if 'showpreset3inmenu' in line:
                    showpreset3set = True
                if 'orientation' in line:
                    orientationset = True
            ConfigFile.close()
            if not currentpresetset or not preset1name1set or not preset1name2set or not preset2name1set or not preset2name2set \
            or not preset3name1set or not preset3name2set or not showpreset2set or not showpreset3set or not orientationset:
                ConfigFile = open(Cooktimer_CfgFile[0],"a")
                if not currentpresetset:
                    ConfigFile.write("currentpreset 1\n")
                if not preset1name1set:
                    ConfigFile.write("preset1name1 \n")
                if not preset1name2set:
                    ConfigFile.write("preset1name2 \n")
                if not preset2name1set:
                    ConfigFile.write("preset2name1 \n")
                if not preset2name2set:
                    ConfigFile.write("preset2name2 \n")
                if not preset3name1set:
                    ConfigFile.write("preset3name1 \n")
                if not preset3name2set:
                    ConfigFile.write("preset3name2 \n")
                if not showpreset2set:
                    ConfigFile.write("showpreset2inmenu false\n")
                if not showpreset3set:
                    ConfigFile.write("showpreset3inmenu false\n")
                if not orientationset:
                    ConfigFile.write("orientation auto\n")
                ConfigFile.close()
        for i in range(1,4):
            if not os.path.isfile(Cooktimer_CfgFile[i]):
                try:
                    newConfigFile = open(Cooktimer_CfgFile[i],"w")
                except:
                    QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_CfgFile[i])
                else:
                    # Import legacy config file if needed
                    if os.path.isfile(Cooktimer_CfgFile_legacy):
                        keepbacklightset = False
                        wakeupset = False
                        vibrationset = False
                        soundset = False
                        ledblinkset = False
                        alarmbannerset = False
                        volsoundset = False
                        alarmfileset = False
                        for line in oldlines:
                            if 'keepbacklighton' in line:
                                newConfigFile.write("keepbacklighton " + cooktimer_opts["keepbacklighton"] + "\n")
                                keepbacklightset = True
                            if 'wakeup' in line:
                                newConfigFile.write("wakeup " + cooktimer_opts["wakeup"] + "\n")
                                wakeupset = True
                            if 'vibration' in line:
                                newConfigFile.write("vibration " + cooktimer_opts["vibration"] + "\n")
                                vibrationset = True
                            if 'sound' in line:
                                newConfigFile.write("sound " + cooktimer_opts["sound"] + "\n")
                                soundset = True
                            if 'ledblink' in line:
                                newConfigFile.write("ledblink " + cooktimer_opts["ledblink"] + "\n")
                                ledblinkset = True
                            if 'alarmbanner' in line:
                                newConfigFile.write("alarmbanner " + cooktimer_opts["alarmbanner"] + "\n")
                                alarmbannerset = True
                            if 'volumelevel' in line:
                                newConfigFile.write("volumelevel " + cooktimer_opts["volumelevel"] + "\n")
                                volsoundset = True
                            if 'alarmfile' in line:
                                newConfigFile.write("alarmfile " + cooktimer_opts["alarmfile"] + "\n")
                                alarmfileset = True
                        if not keepbacklightset:
                            newConfigFile.write("keepbacklighton true\n")
                        if not wakeupset:
                            newConfigFile.write("wakeup true\n")
                        if not vibrationset:
                            newConfigFile.write("vibration true\n")
                        if not soundset:
                            newConfigFile.write("sound true\n")
                        if not ledblinkset:
                            newConfigFile.write("ledblink false\n")
                        if not alarmbannerset:
                            newConfigFile.write("alarmbanner true\n")
                        if not volsoundset:
                            newConfigFile.write("volumelevel 50\n")
                        if not alarmfileset:
                            newConfigFile.write("alarmfile /opt/cooktimer/alarmsounds/cooktimer.mp3\n")
                    else:
                        newConfigFile.write("keepbacklighton true\n")
                        newConfigFile.write("wakeup true\n")
                        newConfigFile.write("vibration true\n")
                        newConfigFile.write("sound true\n")
                        newConfigFile.write("ledblink false\n")
                        newConfigFile.write("alarmbanner true\n")
                        newConfigFile.write("volumelevel 50\n")
                        newConfigFile.write("alarmfile /opt/cooktimer/alarmsounds/cooktimer.mp3\n")
                    newConfigFile.close()
            else:
                keepbacklightset = False
                vibrationset = False
                wakeupset = False
                soundset = False
                ledblinkset = False
                alarmbannerset = False
                volsoundset = False
                alarmfileset = False
                ConfigFile = open(Cooktimer_CfgFile[i],"r")
                lines = ConfigFile.readlines()
                for line in lines:
                    if 'keepbacklighton' in line:
                        keepbacklightset = True
                    if 'vibration' in line:
                        vibrationset = True
                    if 'wakeup' in line:
                        wakeupset = True
                    if 'sound' in line:
                        soundset = True
                    if 'volumelevel' in line:
                        volsoundset = True
                    if 'alarmfile' in line:
                        alarmfileset = True
                    if 'alarmbanner' in line:
                        alarmbannerset = True
                    if 'ledblink' in line:
                        ledblinkset = True
                ConfigFile.close()
                if not keepbacklightset or not vibrationset or not wakeupset or not soundset or not volsoundset \
                or not alarmfileset or not alarmbannerset or not ledblinkset:
                    ConfigFile = open(Cooktimer_CfgFile[i],"a")
                    if not keepbacklightset:
                        ConfigFile.write("keepbacklighton true\n")
                    if not wakeupset:
                        ConfigFile.write("wakeup true\n")
                    if not vibrationset:
                        ConfigFile.write("vibration true\n")
                    if not soundset:
                        ConfigFile.write("sound true\n")
                    if not ledblinkset:
                        ConfigFile.write("ledblink false\n")
                    if not alarmbannerset:
                        ConfigFile.write("alarmbanner true\n")
                    if not volsoundset:
                        ConfigFile.write("volumelevel 50\n")
                    if not alarmfileset:
                        ConfigFile.write("alarmfile /opt/cooktimer/alarmsounds/cooktimer.mp3\n")
                    ConfigFile.close()
        #Delete legacy config file if needed
        if os.path.isfile(Cooktimer_CfgFile_legacy):
            try:
                os.remove(Cooktimer_CfgFile_legacy)
            except:
                QMessageBox.critical(self, "Warning",  "Cannot delete " + Cooktimer_CfgFile_legacy)

        if not os.path.isfile(Cooktimer_ItemFile):
            try:
                newConfigFile = open(Cooktimer_ItemFile,"w")
            except:
                QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)
            else:
                newConfigFile.close()

        if not os.path.isfile(Cooktimer_Start):
            try:
                newItemstartupFile = codecs.open(Cooktimer_Start,"w", encoding="utf-8")
            except:
                QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_Start)
            else:
                # import start items if needed
                if os.path.isfile(Cooktimer_StartItems_legacy):
                    oldItemstartupFile = codecs.open(Cooktimer_StartItems_legacy,"r", encoding="utf-8")
                    oldlines = oldItemstartupFile.readlines()
                    oldItemstartupFile.close()
                    num_lines = len(oldlines)
                    data = ""
                    for count in range(0,num_lines):
                        data += oldlines[count].strip() + "|0|0\n"
                    for count in range(0,3-num_lines):
                        data += "Choose dish|0|0\n"
                    try:
                        os.remove(Cooktimer_StartItems_legacy)
                    except:
                        QMessageBox.critical(self, "Warning",  "Cannot delete " + Cooktimer_StartItems_legacy)
                else:
                    data = "Choose dish|0|0\nChoose dish|0|0\nChoose dish|0|0\n"
                newItemstartupFile.write(data)
                newItemstartupFile.close()

        ###############
        # Create menu #
        ###############
        orientationGroup = QActionGroup(self)
        orientationGroup.setExclusive(True)
        self.landscapeAction = QAction(self.tr('&Landscape') ,self)
        self.landscapeAction.setCheckable(True)
        self.portraitAction = QAction(self.tr('&Portrait') ,self)
        self.portraitAction.setCheckable(True)
        self.autorotateAction = QAction(self.tr('&Autorotate') ,self)
        self.autorotateAction.setCheckable(True)
        orientationGroup.addAction(self.landscapeAction)
        orientationGroup.addAction(self.autorotateAction)
        orientationGroup.addAction(self.portraitAction)

        self.presetsGroup = QActionGroup(self)
        self.presetsGroup.setExclusive(True)
        self.preset1Action = QAction("" ,self)
        self.preset1Action.setCheckable(True)
        self.preset2Action = QAction("" ,self)
        self.preset2Action.setCheckable(True)
        self.preset3Action = QAction("" ,self)
        self.preset3Action.setCheckable(True)
        self.presetsGroup.addAction(self.preset1Action)
        self.presetsGroup.addAction(self.preset2Action)
        self.presetsGroup.addAction(self.preset3Action)

        self.configAction = QAction(self.tr('&Settings'), self)
        editAction = QAction(self.tr('&Edit dishes'), self)
        helpAction = QAction( self.tr('&Help'), self)
        aboutAction = QAction( self.tr('&About'), self)

        ###############
        # read config #
        ###############
        global OptionChar
        global CurrentPreset
        global Preset1name1
        global Preset1name2
        global Preset2name1
        global Preset2name2
        global Preset3name1
        global Preset3name2
        global ShowPreset2
        global ShowPreset3
        global Alarmfile
        global Alarmbanner
        global Wakeup
        global Vibration
        global Ledblink
        global Backlight
        global Volume
        global Sound
        OptionChar = " "
        self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile[0])

        CurrentPreset = int(self.cooktimer_opts["currentpreset"])

        Preset1name1 = self.cooktimer_opts["preset1name1"]
        Preset1name2 = self.cooktimer_opts["preset1name2"]
        Preset2name1 = self.cooktimer_opts["preset2name1"]
        Preset2name2 = self.cooktimer_opts["preset2name2"]
        Preset3name1 = self.cooktimer_opts["preset3name1"]
        Preset3name2 = self.cooktimer_opts["preset3name2"]

        if self.cooktimer_opts["showpreset2inmenu"] == "true":
            ShowPreset2 = True
        if self.cooktimer_opts["showpreset3inmenu"] == "true":
            ShowPreset3 = True

        if self.cooktimer_opts["orientation"] == "portrait":
            self.portraitAction.setChecked(True)
            self.setAttribute(Qt.WA_Maemo5PortraitOrientation, True)
            Orientation = "portrait"
        elif self.cooktimer_opts["orientation"] == "landscape":
            self.landscapeAction.setChecked(True)
            self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)
            Orientation = "landscape"
        else:
            self.autorotateAction.setChecked(True)
            self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
            Orientation = "auto"

        self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile[CurrentPreset])

        if self.cooktimer_opts["keepbacklighton"] == "true":
            Backlight = True
        if self.cooktimer_opts["wakeup"] == "true":
            Wakeup = True
        if self.cooktimer_opts["vibration"] == "true":
            Vibration = True
        if self.cooktimer_opts["sound"] == "true":
            Sound = True
        if self.cooktimer_opts["alarmbanner"] == "true":
            Alarmbanner = True
        if self.cooktimer_opts["ledblink"] == "true":
            Ledblink = True
        Alarmfile = self.cooktimer_opts["alarmfile"]
        Volume = self.cooktimer_opts["volumelevel"]

        ########################
        # create menu from bar #
        ########################
        menubar = self.menuBar()
        mainMenu = menubar.addMenu('&MainMenu')
        mainMenu.addActions(orientationGroup.actions())
        mainMenu.addActions(self.presetsGroup.actions())
        self.setPresetsGroup()
        mainMenu.addAction(self.configAction)
        mainMenu.addAction(editAction)
        mainMenu.addAction(helpAction)
        mainMenu.addAction(aboutAction)


        ##################
        # Define actions #
        ##################
        self.portraitAction.triggered.connect(self.portraitPushed)
        self.landscapeAction.triggered.connect(self.landscapePushed)
        self.autorotateAction.triggered.connect(self.autorotatePushed)
        self.preset1Action.triggered.connect(self.preset1Pushed)
        self.preset2Action.triggered.connect(self.preset2Pushed)
        self.preset3Action.triggered.connect(self.preset3Pushed)
        editAction.triggered.connect(self.editPushed)
        helpAction.triggered.connect(self.helpPushed)
        aboutAction.triggered.connect(self.aboutPushed)
        self.configAction.triggered.connect(self.slotConfig)
        self.connect(self, SIGNAL("didSomething"), self.checkIsDim)

        #############################
        # Prevent backlight dimming #
        #############################
        self.dimtimer = QTimer()
        self.dimtimer.timeout.connect(self.KeepBackLightOn)
        # get timeout value
        self.screendim_timeout = (int(os.popen('gconftool-2 --get /system/osso/dsm/display/display_dim_timeout').read())-1)*1000
        if Backlight:
            self.dimtimer.start(self.screendim_timeout)
        ################################################################
        # set initial orientation to landscape if kb open and portrait #
        ################################################################
        kb_state = os.popen('cat /sys/devices/platform/gpio-switch/slide/state').read().strip()
        if kb_state == "open" and Orientation == "portrait":
            self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)

        self.form_widget = FormWidget(self)
        self.setCentralWidget(self.form_widget)

    def setPresetsGroup(self):
        global CurrentPreset
        global Preset1name1
        global Preset1name2
        global Preset2name1
        global Preset2name2
        global Preset3name1
        global Preset3name2

        if Preset1name1 and Preset1name2:
            Preset1name = Preset1name1 + "\n" + Preset1name2
        else: Preset1name = Preset1name1 + Preset1name2
        if Preset2name1 and Preset2name2:
            Preset2name = Preset2name1 + "\n" + Preset2name2
        else: Preset2name = Preset2name1 + Preset2name2
        if Preset3name1 and Preset3name2:
            Preset3name = Preset3name1 + "\n" + Preset3name2
        else: Preset3name = Preset3name1 + Preset3name2

        if Preset1name:
            self.preset1Action.setText(Preset1name)
        else: self.preset1Action.setText(self.tr('Default'))
        if Preset2name:
            self.preset2Action.setText(Preset2name)
        else: self.preset2Action.setText(self.tr('Preset 2'))
        if Preset3name:
            self.preset3Action.setText(Preset3name)
        else: self.preset3Action.setText(self.tr('Preset 3'))

        if ShowPreset2 or ShowPreset3:
            self.preset1Action.setVisible(True)
        else: self.preset1Action.setVisible(False)
        if ShowPreset2:
            self.preset2Action.setVisible(True)
        else: self.preset2Action.setVisible(False)
        if ShowPreset3:
            self.preset3Action.setVisible(True)
        else: self.preset3Action.setVisible(False)

        if CurrentPreset ==1:
            self.preset1Action.setChecked(True)
        elif CurrentPreset ==2:
            self.preset2Action.setChecked(True)
        else:
            self.preset3Action.setChecked(True)

    def helpPushed(self):
        a = HelpWindow(self)
        a.show()

    def slotConfig(self):
        # show config screen
        a = ConfigWindow(self)
        self.connect(a, SIGNAL("destroyed()"),self.checkIsDim)
        a.show()

    def checkIsDim(self):
        if Backlight and not self.dimtimer.isActive():
            self.dimtimer.start(self.screendim_timeout)
        if not Backlight and self.dimtimer.isActive():
            self.dimtimer.stop()

    def handle_slide(self,var1,var2):
        kb_state = os.popen('cat /sys/devices/platform/gpio-switch/slide/state').read().strip()
        if kb_state == "open" and Orientation == "portrait":
            self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)
        elif Orientation == "portrait":
            self.setAttribute(Qt.WA_Maemo5PortraitOrientation, True)

    def KeepBackLightOn(self):
        strUnlock = "dbus-send --system --type=method_call --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_display_blanking_pause"
        QProcess.startDetached(strUnlock)

    def saveSettings(self):
        self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile[0])
        self.cooktimer_opts["currentpreset"] = str(CurrentPreset)
        self.cooktimer_opts["orientation"] = Orientation
        try:
            newConfigFile = open(Cooktimer_CfgFile[0],"w")
            for option in self.cooktimer_opts:
                newConfigFile.write(option + " " + self.cooktimer_opts[option] + "\n")
            newConfigFile.close()
            msg = self.tr("Configuration is successfully saved")
            os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                string:"'+msg+'"')
        except:
            msg = self.tr("Could NOT save Configuration!")
            os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                string:"'+msg+'"')
        self.checkIsDim()

    def portraitPushed(self):
        global Orientation
        if Orientation != "portrait":
            self.setAttribute(Qt.WA_Maemo5PortraitOrientation, True)
            Orientation = "portrait"
            self.saveSettings()

    def landscapePushed(self):
        global Orientation
        if Orientation != "landscape":
            self.setAttribute(Qt.WA_Maemo5LandscapeOrientation, True)
            Orientation = "landscape"
            self.saveSettings()

    def autorotatePushed(self):
        global Orientation
        if Orientation != "auto":
            self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
            Orientation = "auto"
            self.saveSettings()

    def preset1Pushed(self):
        global CurrentPreset
        if CurrentPreset != 1:
            CurrentPreset = 1
            self.presetChanged()

    def preset2Pushed(self):
        global CurrentPreset
        if CurrentPreset != 2:
            CurrentPreset = 2
            self.presetChanged()

    def preset3Pushed(self):
        global CurrentPreset
        if CurrentPreset != 3:
            CurrentPreset = 3
            self.presetChanged()

    def presetChanged(self):
        global Backlight
        global Wakeup
        global Vibration
        global Sound
        global Ledblink
        global Alarmbanner
        global Volume
        global Alarmfile
        global OptionChar
        OptionChar = " "
        self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile[CurrentPreset])
        if self.cooktimer_opts["keepbacklighton"] == "true":
            Backlight = True
        else: Backlight = False
        if self.cooktimer_opts["wakeup"] == "true":
            Wakeup = True
        else: Wakeup = False
        if self.cooktimer_opts["vibration"] == "true":
            Vibration = True
        else: Vibration = False
        if self.cooktimer_opts["sound"] == "true":
            Sound = True
        else: Sound = False
        if self.cooktimer_opts["ledblink"] == "true":
            Ledblink = True
        else: Ledblink = False
        if self.cooktimer_opts["alarmbanner"] == "true":
            Alarmbanner = True
        else: Alarmbanner = False
        Volume = self.cooktimer_opts["volumelevel"]
        Alarmfile = self.cooktimer_opts["alarmfile"]

        self.saveSettings()

    def editPushed(self):
        widget = itemWindow(self)
        widget.show()

    def aboutPushed(self):
        d = QDialog(self)
        vbox = QVBoxLayout()
        verticalLayout = QVBoxLayout()
        d.setWindowTitle(self.tr("About")+" cooktimer")
        verticalLayout.addWidget(QLabel("<center><img src=/opt/usr/share/icons/hicolor/64x64/apps/cooktimer.png /></center>"),0)
        verticalLayout.addWidget(QLabel("<center><b><big>Cooktimer "+CooktimerVersion+"<big></b></center>"),1)
        verticalLayout.addWidget(QLabel("<center>"+self.tr("Created by")+" Arno Dekker (ade)</center>"),2)
        verticalLayout.addWidget(QLabel("<center><small>"+self.tr("Assistance by")+" Marc P"+"\xc3\xb6".decode('utf-8')+"pperl (rasmarc)</small></center><br>"),3)
        vbox.addLayout (verticalLayout)
        d.setLayout(vbox)
        d.show()

class HelpWindow(QMainWindow):
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle(self.tr("Help"))
        self.setAttribute(Qt.WA_Maemo5StackedWindow)
        self.setAttribute(Qt.WA_DeleteOnClose)
        area = QScrollArea()
        lay = QHBoxLayout()
        lay.addWidget(area)
        self.wg = QWidget()
        area.setWidget(self.wg)
        self.setCentralWidget(area)
        self.wg.resize(478, 740)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.wg.sizePolicy().hasHeightForWidth())
        self.wg.setSizePolicy(sizePolicy)
        grid = QGridLayout(self.wg)
        infoTXT = "<font style='color: black'>" \
            "<center><h3>"+self.tr("Cooktimer")+"</b></center></h3>" \
            +self.tr("Cooktimer provides three timers for preparing the perfect meal.") + "<p>" \
            +self.tr("Apart from the obvious functions and settings, there are some not so easily spotted:") \
            + "<UL>" \
            "<LI>" + self.tr("Pressing a running timer bar will pause the alarm") + \
            "<LI>" + self.tr("Pressing a paused timer bar will unpause the alarm") + \
            "<LI>" + self.tr("Pressing a timer bar after showing \"00:00:00\" will silence it's alarm") + \
            "<LI>" + self.tr("Long-pressing a dishpicker will show all dish info with interim messages and notes") + \
            "<LI>" + self.tr("Long-pressing a startbutton will show a timer menu where you can reset a timer and choose startup settings") + \
            "<LI>" + self.tr("Long-pressing a timepicker will toggle continue mode") + \
            "<LI>" + self.tr("Long-pressing a timer bar will toggle stopwatch mode") + \
            "<LI>" + self.tr("In settings menu \"presets\" can be activated to show up in the main menu for changing settings quickly") + \
            "</UL>"
        termsInfo = QTextBrowser()
        termsInfo.setMinimumSize(QSize(330, 340))
        termsInfo.setHtml( infoTXT )
        font = QFont()
        font.setPointSize(16)
        termsInfo.setFont(font)
        grid.addWidget(termsInfo, 0, 0)
        self.wg.show()
        self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
        # set correct orientation at start
        self.orientationChanged()

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() < screenGeometry.height():
            # portrait
            self.wg.resize(478, 740)
        else:
            self.wg.resize(792, 420)

class ConfigWindow(QMainWindow):
    def __init__(self,parent):
        QMainWindow.__init__(self,parent)
        self.setWindowTitle(self.tr("Configuration cooktimer"))
        self.setAttribute(Qt.WA_Maemo5StackedWindow)
        self.setAttribute(Qt.WA_DeleteOnClose)

        self.window = QWidget(self)
        self.layoutWindow = QGridLayout()
        self.window.setLayout(self.layoutWindow)

        self.areaScrolling = QScrollArea()
        widgetScrolling = QWidget()
        layoutScrolling = QGridLayout()
        widgetScrolling.setLayout(layoutScrolling)
        self.areaScrolling.setWidget(widgetScrolling)
        self.areaScrolling.setWidgetResizable(True)

        self.widgetButtons1 = QWidget()
        self.layoutButtons1 = QGridLayout()
        self.layoutButtons1.setContentsMargins(0,0,0,0)
        self.widgetButtons1.setLayout(self.layoutButtons1)

        self.widgetButtons2 = QWidget()
        self.layoutButtons2 = QGridLayout()
        self.layoutButtons2.setContentsMargins(0,0,0,0)
        self.widgetButtons2.setLayout(self.layoutButtons2)

        # preset
        global presetNbr
        presetNbr = CurrentPreset
        self.showPresetCheckbox = QCheckBox(self.tr("Show in menu"), self)
        self.presetNameEdit1 = QLineEdit()
        self.presetNameEdit2 = QLineEdit()
        self.presetNameEdit1.setPlaceholderText(self.tr("Description"))
        self.presetNameEdit2.setPlaceholderText(self.tr("[Second line]"))

        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)

        # define checkboxes
        self.backlightCheckbox = QCheckBox(self.tr("Keep backlight on"),self)
        self.backlightCheckbox.setMinimumWidth(370)
        self.screenwakeupCheckbox = QCheckBox(self.tr("Wakeup screen on alarm"),self)
        self.vibrateCheckbox = QCheckBox(self.tr("Vibrate on alarm"),self)
        self.ledCheckbox = QCheckBox(self.tr("Led blink on alarm"),self)
        self.soundCheckbox = QCheckBox(self.tr("Sound on alarm"),self)
        self.bannerCheckbox = QCheckBox(self.tr("Alarm banner"),self)
        self.volSlider = QSlider(Qt.Horizontal, self)
        self.volSlider.setMinimum(0);
        self.volSlider.setMaximum(100);
        self.volSlider.setValue(int(Volume))
        self.volLabel = QPushButton()
        self.volLabel.setStyleSheet("background: transparent; border: none")
        self.volLabel.setMaximumHeight(60)
        # define alarmfile button
        globals()['alarmfilePicker'] = QMaemo5ValueButton(self.tr('&Alarm sound'), self)
        globals()['alarmfilePicker'].setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
        # define preset buttons
        self.preset1Button = QRadioButton(self.tr("Preset 1"),self)
        self.preset1Button.setMinimumWidth(160)
        self.preset2Button = QRadioButton(self.tr("Preset 2"),self)
        self.preset2Button.setMinimumWidth(160)
        self.preset3Button = QRadioButton(self.tr("Preset 3"),self)
        self.preset3Button.setMinimumWidth(160)

        groupPresets = QButtonGroup()
        groupPresets.addButton(self.preset1Button)
        groupPresets.addButton(self.preset2Button)
        groupPresets.addButton(self.preset3Button)

        if presetNbr == 1:
            self.preset1Button.setChecked(True)
        elif presetNbr == 2:
            self.preset2Button.setChecked(True)
        else:
            self.preset3Button.setChecked(True)

        self.saveConfigButton = QPushButton(self.tr("Done"),self)
        self.saveConfigButton.setMinimumWidth(160)

        layoutScrolling.addWidget(self.showPresetCheckbox,0,0,1,2)
        layoutScrolling.addWidget(self.presetNameEdit1,1,0,1,1)
        layoutScrolling.addWidget(self.presetNameEdit2,1,1,1,1)
        layoutScrolling.addWidget(separator,2,0,1,2)
        layoutScrolling.addWidget(self.backlightCheckbox,3,0,1,2)
        layoutScrolling.addWidget(self.screenwakeupCheckbox,4,0,1,2)
        layoutScrolling.addWidget(self.vibrateCheckbox,5,0,1,2)
        layoutScrolling.addWidget(self.soundCheckbox,6,0,1,2)
        layoutScrolling.addWidget(self.ledCheckbox,7,0,1,2)
        layoutScrolling.addWidget(self.bannerCheckbox,8,0,1,2)
        layoutScrolling.addWidget(self.volLabel,9,0,1,2)
        layoutScrolling.addWidget(self.volSlider,10,0,1,2)
        layoutScrolling.addWidget(globals()['alarmfilePicker'],11,0,1,2)

        # define indexed variables
        global temp_ShowPreset
        global temp_Presetname1
        global temp_Presetname2
        global temp_Backlight
        global temp_Wakeup
        global temp_Vibration
        global temp_Sound
        global temp_Ledblink
        global temp_Alarmbanner
        global temp_Volume
        global temp_Alarmfile
        temp_ShowPreset = range(4)
        temp_Presetname1 = range(4)
        temp_Presetname2 = range(4)
        temp_Backlight = range(4)
        temp_Wakeup = range(4)
        temp_Vibration = range(4)
        temp_Sound = range(4)
        temp_Ledblink = range(4)
        temp_Alarmbanner = range(4)
        temp_Volume = range(4)
        temp_Alarmfile = range(4)

        # fetch values
        temp_ShowPreset[1] = ShowPreset1
        temp_ShowPreset[2] = ShowPreset2
        temp_ShowPreset[3] = ShowPreset3
        temp_Presetname1[1] = Preset1name1
        temp_Presetname2[1] = Preset1name2
        temp_Presetname1[2] = Preset2name1
        temp_Presetname2[2] = Preset2name2
        temp_Presetname1[3] = Preset3name1
        temp_Presetname2[3] = Preset3name2

        global OptionChar
        OptionChar = " "
        for i in range(1,4):
            temp_Backlight[i] = False
            temp_Wakeup[i] = False
            temp_Vibration[i] = False
            temp_Sound[i] = False
            temp_Ledblink[i] = False
            temp_Alarmbanner[i] = False
            self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile[i])
            if self.cooktimer_opts["keepbacklighton"] == "true":
                temp_Backlight[i] = True
            if self.cooktimer_opts["wakeup"] == "true":
                temp_Wakeup[i] = True
            if self.cooktimer_opts["vibration"] == "true":
                temp_Vibration[i] = True
            if self.cooktimer_opts["sound"] == "true":
                temp_Sound[i] = True
            if self.cooktimer_opts["ledblink"] == "true":
                temp_Ledblink[i] = True
            if self.cooktimer_opts["alarmbanner"] == "true":
                temp_Alarmbanner[i] = True
            temp_Volume[i] = self.cooktimer_opts["volumelevel"]
            temp_Alarmfile[i] = self.cooktimer_opts["alarmfile"]

        self.setPresetOptions()

        # set correct layout
        self.orientationChanged()
        self.window.show()
        # signals
        self.preset1Button.clicked.connect(self.changePreset)
        self.preset2Button.clicked.connect(self.changePreset)
        self.preset3Button.clicked.connect(self.changePreset)
        self.showPresetCheckbox.clicked.connect(self.togglePresetname)
        self.volSlider.valueChanged[int].connect(self.volChange)
        globals()['alarmfilePicker'].clicked.connect(self.alarmfilePushed)
        self.saveConfigButton.clicked.connect(self.saveConfig)
        self.saveConfigButton.clicked.connect(parent.setPresetsGroup)
        self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        # first remove layout
        self.layoutWindow.removeWidget(self.areaScrolling)
        self.layoutWindow.removeWidget(self.widgetButtons1)
        self.layoutWindow.removeWidget(self.widgetButtons2)
        self.layoutButtons1.removeWidget(self.preset1Button)
        self.layoutButtons1.removeWidget(self.preset2Button)
        self.layoutButtons1.removeWidget(self.preset3Button)
        self.layoutButtons2.removeWidget(self.saveConfigButton)
        # landscape
        if screenGeometry.width() > screenGeometry.height():
            self.window.resize(800,424)
            # add layout
            self.layoutButtons1.addWidget(self.preset1Button,0,0,Qt.AlignTop)
            self.layoutButtons1.addWidget(self.preset2Button,1,0,Qt.AlignTop)
            self.layoutButtons1.addWidget(self.preset3Button,2,0,Qt.AlignTop)
            self.layoutButtons2.addWidget(self.saveConfigButton,0,0,Qt.AlignBottom)
            self.layoutWindow.addWidget(self.areaScrolling,0,0,2,1)
            self.layoutWindow.addWidget(self.widgetButtons1,0,1)
            self.layoutWindow.addWidget(self.widgetButtons2,1,1)
            globals()['alarmfilePicker'].setMaximumWidth(555)
        # portrait
        else:
            self.window.resize(480,744)
            # add layout
            self.layoutButtons1.addWidget(self.preset1Button,0,0)
            self.layoutButtons1.addWidget(self.preset2Button,0,1)
            self.layoutButtons1.addWidget(self.preset3Button,0,2)
            self.layoutButtons2.addWidget(self.saveConfigButton,0,0)
            self.layoutWindow.addWidget(self.widgetButtons1,0,0)
            self.layoutWindow.addWidget(self.areaScrolling,1,0)
            self.layoutWindow.addWidget(self.widgetButtons2,2,0)
            globals()['alarmfilePicker'].setMaximumWidth(408)

    def changePreset(self):
        global presetNbr
        global temp_ShowPreset
        global temp_Presetname1
        global temp_Presetname2
        global temp_Backlight
        global temp_Wakeup
        global temp_Vibration
        global temp_Sound
        global temp_Ledblink
        global temp_Alarmbanner
        global temp_Volume
        global temp_Alarmfile

        if self.showPresetCheckbox.isChecked():
            temp_ShowPreset[presetNbr] = True
        else: temp_ShowPreset[presetNbr] = False
        temp_Presetname1[presetNbr] = self.presetNameEdit1.text()
        temp_Presetname2[presetNbr] = self.presetNameEdit2.text()
        if self.backlightCheckbox.isChecked():
            temp_Backlight[presetNbr] = True
        else: temp_Backlight[presetNbr] = False
        if self.screenwakeupCheckbox.isChecked():
            temp_Wakeup[presetNbr] = True
        else: temp_Wakeup[presetNbr] = False
        if self.vibrateCheckbox.isChecked():
            temp_Vibration[presetNbr] = True
        else: temp_Vibration[presetNbr] = False
        if self.soundCheckbox.isChecked():
            temp_Sound[presetNbr] = True
        else: temp_Sound[presetNbr] = False
        if self.ledCheckbox.isChecked():
            temp_Ledblink[presetNbr] = True
        else: temp_Ledblink[presetNbr] = False
        if self.bannerCheckbox.isChecked():
            temp_Alarmbanner[presetNbr] = True
        else: temp_Alarmbanner[presetNbr] = False
        temp_Volume[presetNbr] = self.volSlider.value()
        temp_Alarmfile[presetNbr] = globals()['alarmfilePicker'].valueText()

        if self.preset1Button.isChecked():
            presetNbr = 1
        elif self.preset2Button.isChecked():
            presetNbr = 2
        else:
            presetNbr = 3

        self.setPresetOptions()

    def setPresetOptions(self):
        if presetNbr == 1:
            self.showPresetCheckbox.setEnabled(False)
        else: self.showPresetCheckbox.setEnabled(True)
        if temp_ShowPreset[presetNbr]:
            self.showPresetCheckbox.setChecked(True)
            self.presetNameEdit1.setEnabled(True)
            self.presetNameEdit2.setEnabled(True)
        else:
            self.showPresetCheckbox.setChecked(False)
            self.presetNameEdit1.setEnabled(False)
            self.presetNameEdit2.setEnabled(False)
        self.presetNameEdit1.setText(temp_Presetname1[presetNbr])
        self.presetNameEdit2.setText(temp_Presetname2[presetNbr])
        if temp_ShowPreset[presetNbr]:
            self.showPresetCheckbox.setChecked(True)
        else: self.showPresetCheckbox.setChecked(False)
        if temp_Backlight[presetNbr]:
            self.backlightCheckbox.setChecked(True)
        else: self.backlightCheckbox.setChecked(False)
        if temp_Wakeup[presetNbr]:
            self.screenwakeupCheckbox.setChecked(True)
        else: self.screenwakeupCheckbox.setChecked(False)
        if temp_Vibration[presetNbr]:
            self.vibrateCheckbox.setChecked(True)
        else: self.vibrateCheckbox.setChecked(False)
        if temp_Sound[presetNbr]:
            self.soundCheckbox.setChecked(True)
        else: self.soundCheckbox.setChecked(False)
        if temp_Alarmbanner[presetNbr]:
            self.bannerCheckbox.setChecked(True)
        else: self.bannerCheckbox.setChecked(False)
        if temp_Ledblink[presetNbr]:
            self.ledCheckbox.setChecked(True)
        else: self.ledCheckbox.setChecked(False)
        self.volChange(int(temp_Volume[presetNbr]))
        self.volSlider.setValue(int(temp_Volume[presetNbr]))
        globals()['alarmfilePicker'].setValueText(temp_Alarmfile[presetNbr])

    def togglePresetname(self):
        if self.showPresetCheckbox.isChecked():
            self.presetNameEdit1.setEnabled(True)
            self.presetNameEdit2.setEnabled(True)
        else:
            self.presetNameEdit1.setEnabled(False)
            self.presetNameEdit2.setEnabled(False)

    def alarmfilePushed(self):
        widget = fileWindow(self)
        widget.show()

    def volChange(self,value):
        if value > 0 and value < 100:
            self.volLabel.setText(self.tr("Alarm volume: ") + str(value))
        if value == 0:
            self.volLabel.setIcon(QIcon.fromTheme("statusarea_volume_mute"))
            self.volLabel.setText(self.tr("Alarm muted"))
        elif value > 0 and value <= 30:
            self.volLabel.setIcon(QIcon.fromTheme("statusarea_volumelevel1"))
        elif value > 30 and value <= 60:
            self.volLabel.setIcon(QIcon.fromTheme("statusarea_volumelevel2"))
        elif value > 60 and value <= 90:
            self.volLabel.setIcon(QIcon.fromTheme("statusarea_volumelevel3"))
        elif value > 90 and value <= 99:
            self.volLabel.setIcon(QIcon.fromTheme("statusarea_volumelevel4"))
        else:
            self.volLabel.setIcon(QIcon.fromTheme("statusarea_volumelevel4"))
            self.volLabel.setText(self.tr("Alarm volume: max"))

    def saveConfig(self):
        global CurrentPreset
        global ShowPreset2
        global ShowPreset3
        global Preset1name1
        global Preset1name2
        global Preset2name1
        global Preset2name2
        global Preset3name1
        global Preset3name2
        global Backlight
        global Wakeup
        global Vibration
        global Sound
        global Ledblink
        global Alarmbanner
        global Volume
        global Alarmfile
        global temp_ShowPreset
        global temp_Presetname1
        global temp_Presetname2
        global temp_Backlight
        global temp_Wakeup
        global temp_Vibration
        global temp_Sound
        global temp_Ledblink
        global temp_Alarmbanner
        global temp_Volume
        global temp_Alarmfile

        if self.showPresetCheckbox.isChecked():
            temp_ShowPreset[presetNbr] = True
        else: temp_ShowPreset[presetNbr] = False
        temp_Presetname1[presetNbr] = self.presetNameEdit1.text()
        temp_Presetname2[presetNbr] = self.presetNameEdit2.text()
        if self.backlightCheckbox.isChecked():
            temp_Backlight[presetNbr] = True
        else: temp_Backlight[presetNbr] = False
        if self.screenwakeupCheckbox.isChecked():
            temp_Wakeup[presetNbr] = True
        else: temp_Wakeup[presetNbr] = False
        if self.vibrateCheckbox.isChecked():
            temp_Vibration[presetNbr] = True
        else: temp_Vibration[presetNbr] = False
        if self.soundCheckbox.isChecked():
            temp_Sound[presetNbr] = True
        else: temp_Sound[presetNbr] = False
        if self.ledCheckbox.isChecked():
            temp_Ledblink[presetNbr] = True
        else: temp_Ledblink[presetNbr] = False
        if self.bannerCheckbox.isChecked():
            temp_Alarmbanner[presetNbr] = True
        else: temp_Alarmbanner[presetNbr] = False
        temp_Volume[presetNbr] = self.volSlider.value()
        temp_Alarmfile[presetNbr] = globals()['alarmfilePicker'].valueText()

        ShowPreset2 = temp_ShowPreset[2]
        ShowPreset3 = temp_ShowPreset[3]
        Preset1name1 = temp_Presetname1[1]
        Preset1name2 = temp_Presetname2[1]
        Preset2name1 = temp_Presetname1[2]
        Preset2name2 = temp_Presetname2[2]
        Preset3name1 = temp_Presetname1[3]
        Preset3name2 = temp_Presetname2[3]

        if (CurrentPreset == 2 and not ShowPreset2) or (CurrentPreset == 3 and not ShowPreset3):
            CurrentPreset = 1

        Backlight = temp_Backlight[CurrentPreset]
        Wakeup = temp_Wakeup[CurrentPreset]
        Vibration = temp_Vibration[CurrentPreset]
        Sound = temp_Sound[CurrentPreset]
        Ledblink = temp_Ledblink[CurrentPreset]
        Alarmbanner = temp_Alarmbanner[CurrentPreset]
        Volume = temp_Volume[CurrentPreset]
        Alarmfile = temp_Alarmfile[CurrentPreset]

        self.saveSettings()

    def saveSettings(self):
        global OptionChar
        global temp_ShowPreset
        global temp_Presetname1
        global temp_Presetname2
        global temp_Backlight
        global temp_Wakeup
        global temp_Vibration
        global temp_Sound
        global temp_Ledblink
        global temp_Alarmbanner
        global temp_Volume
        global temp_Alarmfile
        OptionChar = " "
        self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile[0])
        self.cooktimer_opts["currentpreset"] = str(CurrentPreset)
        self.cooktimer_opts["preset1name1"] = Preset1name1
        self.cooktimer_opts["preset1name2"] = Preset1name2
        self.cooktimer_opts["preset2name1"] = Preset2name1
        self.cooktimer_opts["preset2name2"] = Preset2name2
        self.cooktimer_opts["preset3name1"] = Preset3name1
        self.cooktimer_opts["preset3name2"] = Preset3name2
        if ShowPreset2:
            self.cooktimer_opts["showpreset2inmenu"] = "true"
        else: self.cooktimer_opts["showpreset2inmenu"] = "false"
        if ShowPreset3:
            self.cooktimer_opts["showpreset3inmenu"] = "true"
        else: self.cooktimer_opts["showpreset3inmenu"] = "false"
        successMsg = True
        try:
            newConfigFile = open(Cooktimer_CfgFile[0],"w")
            for option in self.cooktimer_opts:
                newConfigFile.write(option + " " + self.cooktimer_opts[option] + "\n")
            newConfigFile.close()
        except:
            successMsg = False

        for i in range(1,4):
            self.cooktimer_opts = parse_config(self,Cooktimer_CfgFile[i])
            if temp_Backlight[i]:
                self.cooktimer_opts["keepbacklighton"] = "true"
            else: self.cooktimer_opts["keepbacklighton"] = "false"
            if temp_Wakeup[i]:
                self.cooktimer_opts["wakeup"] = "true"
            else: self.cooktimer_opts["wakeup"] = "false"
            if temp_Vibration[i]:
                self.cooktimer_opts["vibration"] = "true"
            else: self.cooktimer_opts["vibration"] = "false"
            if temp_Sound[i]:
                self.cooktimer_opts["sound"] = "true"
            else: self.cooktimer_opts["sound"] = "false"
            if temp_Ledblink[i]:
                self.cooktimer_opts["ledblink"] = "true"
            else: self.cooktimer_opts["ledblink"] = "false"
            if temp_Alarmbanner[i]:
                self.cooktimer_opts["alarmbanner"] = "true"
            else: self.cooktimer_opts["alarmbanner"] = "false"
            self.cooktimer_opts["volumelevel"] = str(temp_Volume[i])
            self.cooktimer_opts["alarmfile"] = temp_Alarmfile[i]
            try:
                newConfigFile = open(Cooktimer_CfgFile[i],"w")
                for option in self.cooktimer_opts:
                    newConfigFile.write(option + " " + self.cooktimer_opts[option] + "\n")
                newConfigFile.close()
            except:
                successMsg = False

        if successMsg:
            msg = self.tr("Configuration is successfully saved")
            os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                string:"'+msg+'"')
        else:
            msg = self.tr("Could NOT save Configuration!")
            os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                string:"'+msg+'"')

        temp_ShowPreset = range(0)
        temp_Presetname1 = range(0)
        temp_Presetname2 = range(0)
        temp_Backlight = range(0)
        temp_Wakeup = range(0)
        temp_Vibration = range(0)
        temp_Sound = range(0)
        temp_Ledblink = range(0)
        temp_Alarmbanner = range(0)
        temp_Volume = range(0)
        temp_Alarmfile = range(0)

        self.emit(SIGNAL("didSomething"))
        self.close()

class itemWindow(QMainWindow):
    def __init__(self,parent):
        QMainWindow.__init__(self,parent)
        self.setWindowTitle(self.tr("Dishes"))
        self.setAttribute(Qt.WA_Maemo5StackedWindow)
        self.setAttribute(Qt.WA_DeleteOnClose)

        global OptionChar

        self.window = QWidget(self)
        self.layoutScrolling = QGridLayout()
        self.layoutScrolling.setAlignment(Qt.AlignVCenter)
        widgetScrolling = QWidget()
        widgetScrolling.setLayout(self.layoutScrolling)

        self.areaScrolling = QScrollArea()
        self.areaScrolling.setWidget(widgetScrolling)
        self.areaScrolling.setWidgetResizable(True)

        self.layoutButtons = QGridLayout()
        self.layoutButtons.setAlignment(Qt.AlignBottom)
        self.layoutButtons.setContentsMargins(0,0,0,0)
        self.widgetButtons = QWidget()
        self.widgetButtons.setLayout(self.layoutButtons)

        self.layoutWindow = QGridLayout()
        self.window.setLayout(self.layoutWindow)
        self.layoutWindow.addWidget(self.areaScrolling,0,0)

        self.addItemButton = QPushButton(self.tr("New"),self)
        self.addItemButton.setMinimumWidth(160)

        self.saveItemButton = QPushButton(self.tr("Done"),self)
        self.saveItemButton.setMinimumWidth(160)

        OptionChar =  '|'
        cooktimer_items = parse_config(self,Cooktimer_ItemFile)
        self.maxLen=25
        self.teller=1
        self.var_num=1
        DishList = ""
        # make a new list for sorting case-insensitive
        for item in cooktimer_items:
            DishList = DishList + item + '|' + cooktimer_items[item] + "\n"
        contentsList = DishList.split('\n')
        contentsList = contentsList[:-1]
        contentsList.sort(lambda a, b: cmp(a.upper(), b.upper()))
        self.signalMapper = QSignalMapper(self)
        for dish in contentsList:
            item, value  = dish.split('|',1)
            hh_mi_ss = cooktimer_items[item][:8].split(':',2)
            hh = hh_mi_ss[0]
            mi = hh_mi_ss[1]
            ss = hh_mi_ss[2]
            globals()['Item%s' % self.var_num] = QMaemo5ValueButton(item)
            globals()['Item%s' % self.var_num].setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
            globals()['Item%s' % self.var_num].setValueText(hh+":"+mi+":"+ss)
            globals()['Item%s' % self.var_num].setStatusTip(cooktimer_items[item])
            if os.path.isfile(Cooktimer_NotesDir + item + ".txt"):
                globals()['Item%s' % self.var_num].setIcon(QIcon("/opt/cooktimer/icons/notes_white.png"))
                globals()['Item%s' % self.var_num].setIconSize(QSize(18,14))
            self.layoutScrolling.addWidget(globals()['Item%s' % self.var_num], self.teller - 1, 0)
            self.signalMapper.setMapping(globals()['Item%s' % self.var_num],-self.var_num)
            globals()['Item%s' % self.var_num].clicked.connect(self.signalMapper, SLOT("map()"))

            globals()['clearButton%s' % self.var_num] = QPushButton()
            globals()['clearButton%s' % self.var_num].setMaximumWidth(48)
            globals()['clearButton%s' % self.var_num].setIcon(QIcon.fromTheme("general_delete"))
            globals()['clearButton%s' % self.var_num].setStyleSheet("background: transparent; border: none")
            self.layoutScrolling.addWidget(globals()['clearButton%s' % self.var_num], self.teller - 1, 1)
            self.signalMapper.setMapping(globals()['clearButton%s' % self.var_num],self.var_num)
            globals()['clearButton%s' % self.var_num].clicked.connect(self.signalMapper, SLOT("map()"))

            self.teller +=1
            self.var_num +=1

        self.connect(self.signalMapper, SIGNAL("mapped(int)"), self.Clear)
        self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
        self.connect(self.addItemButton, SIGNAL("clicked()"),self.Additems)
        self.connect(self.saveItemButton, SIGNAL("clicked()"),self.Saveitems)

        self.orientationChanged()
        self.window.show()

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
            # landscape
            self.window.resize(800,424)
            self.layoutWindow.removeWidget(self.widgetButtons)
            self.layoutButtons.removeWidget(self.addItemButton)
            self.layoutButtons.removeWidget(self.saveItemButton)
            self.layoutButtons.addWidget(self.addItemButton,0,0,Qt.AlignBottom)
            self.layoutButtons.addWidget(self.saveItemButton,1,0,Qt.AlignBottom)
            self.layoutWindow.addWidget(self.widgetButtons,0,1)
            self.addItemButton.setMaximumWidth(160)
            self.saveItemButton.setMaximumWidth(160)
        else:
            # portrait
            self.window.resize(480,744)
            self.layoutWindow.removeWidget(self.widgetButtons)
            self.layoutButtons.removeWidget(self.addItemButton)
            self.layoutButtons.removeWidget(self.saveItemButton)
            self.layoutButtons.addWidget(self.addItemButton,0,0)
            self.layoutButtons.addWidget(self.saveItemButton,0,1)
            self.layoutWindow.addWidget(self.widgetButtons,1,0)
            self.addItemButton.setMaximumWidth(240)
            self.saveItemButton.setMaximumWidth(240)

    def Clear(self,waarde):
        # waarde equals rownbr
        if waarde < 0:
            global rowNbr
            global newdish
            rowNbr = abs(waarde)
            newdish = False
            widget = editItemWindow(self)
            widget.show()
        else:
            if globals()['Item%s' % waarde].isEnabled():
                globals()['Item%s' % waarde].setEnabled(False)
                if globals()['Item%s' % waarde].icon():
                    globals()['Item%s' % waarde].setIcon(QIcon("/opt/cooktimer/icons/notes_grey.png"))
            else:
                globals()['Item%s' % waarde].setEnabled(True)
                if globals()['Item%s' % waarde].icon():
                    globals()['Item%s' % waarde].setIcon(QIcon("/opt/cooktimer/icons/notes_white.png"))

    def Saveitems(self):
        try:
            newItemFile = codecs.open(Cooktimer_ItemFile,"w", encoding="utf-8")
        except:
            QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)
        else:
            for count in range(1,self.teller):
                if globals()['Item%s' % count].isEnabled():
                    allInfo = globals()['Item%s' % count].statusTip().split('|')
                    itemtxt = globals()['Item%s' % count].valueText()
                    if len(allInfo) > 1:
                        msgTxt1 = allInfo[1]
                        msgTime1 = allInfo[2].strip()
                        itemtxt = itemtxt + '|' + msgTxt1 + '|' + msgTime1
                    if len(allInfo) > 3:
                        msgTxt2 = allInfo[3]
                        msgTime2 = allInfo[4].strip()
                        itemtxt = itemtxt + '|' + msgTxt2 + '|' + msgTime2
                    if len(allInfo) > 5:
                        msgTxt3 = allInfo[5]
                        msgTime3 = allInfo[6].strip()
                        itemtxt = itemtxt + '|' + msgTxt3 + '|' + msgTime3
                    if globals()['Item%s' % count ].text() != "":
                        newItemFile.write(globals()['Item%s' % count ].text() + "|" + \
                        itemtxt + "\n")
                else:
                    notesFile = Cooktimer_NotesDir + globals()['Item%s' % count].text() + ".txt"
                    if os.path.isfile(notesFile):
                        os.remove(notesFile)
            newItemFile.close()
            # check startup items
            file = codecs.open(Cooktimer_Start,"r", encoding="utf-8")
            data = file.readlines()
            file.close()
            f = codecs.open(Cooktimer_ItemFile,"r", encoding="utf-8")
            lines = f.readlines()
            f.close()
            rewriteFile = False
            for count in range(0,3):
                foundInItems = False
                if not data[count].split("|")[0] == "Choose dish":
                    for count2 in range(0,len(lines)):
                        if  data[count].split("|")[0] == lines[count2].split("|")[0]:
                            foundInItems = True
                    if not foundInItems:
                        rewriteFile = True
                        # orphaned dish, remove it
                        data[count] = "Choose dish|0|0\n"
            if rewriteFile:
                file = codecs.open(Cooktimer_Start,"w", encoding="utf-8")
                data = "".join(data)
                file.write(data)
                file.close()
            msg = self.tr("Dish list is successfully saved")
            os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                string:"'+msg+'"')
        self.close()

    def Additems(self):
        global newdish
        newdish = True

        globals()['Item%s' % self.var_num] = QMaemo5ValueButton()
        globals()['Item%s' % self.var_num].setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
        self.layoutScrolling.addWidget(globals()['Item%s' % self.var_num], self.teller - 1, 0)
        globals()['Item%s' % self.var_num].hide()
        self.signalMapper.setMapping(globals()['Item%s' % self.var_num],-self.var_num)
        globals()['Item%s' % self.var_num].clicked.connect(self.signalMapper, SLOT("map()"))

        globals()['clearButton%s' % self.var_num] = QPushButton()
        globals()['clearButton%s' % self.var_num].setMaximumWidth(48)
        globals()['clearButton%s' % self.var_num].setIcon(QIcon.fromTheme("general_delete"))
        globals()['clearButton%s' % self.var_num].setStyleSheet("background: transparent; border: none")
        self.layoutScrolling.addWidget(globals()['clearButton%s' % self.var_num], self.teller - 1, 1)
        self.signalMapper.setMapping(globals()['clearButton%s' % self.var_num],self.var_num)
        globals()['clearButton%s' % self.var_num].clicked.connect(self.signalMapper, SLOT("map()"))
        globals()['clearButton%s' % self.var_num].hide()

        self.teller +=1
        self.var_num +=1
        widget = editItemWindow(self)
        widget.show()

class fileWindow(QWidget):
    def __init__(self,parent):
        super(fileWindow, self).__init__(parent)
        self.wg = QDialog(self)
        self.wg.resize(398, 692)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.wg.sizePolicy().hasHeightForWidth())
        self.wg.setSizePolicy(sizePolicy)

        self.wg.setWindowTitle(self.tr("Choose soundfile"))
        # folderbutton up
        self.folderButton_up = QPushButton(self.wg)
        self.folderButton_up.setIcon(QIcon.fromTheme("filemanager_folder_up"))
        self.folderButton_up.setMinimumSize(QSize(74,70))
        self.folderButton_up.setMaximumSize(QSize(74,70))
        # folder display
        self.folderButton = QMaemo5ValueButton(self.wg)
        self.folderButton.setIcon(QIcon.fromTheme("general_folder"))
        self.folderButton.setMinimumSize(QSize(0,70))
        # file list
        self.listWidget = QListWidget(self.wg)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHeightForWidth(self.listWidget.sizePolicy().hasHeightForWidth())
        self.listWidget.setSizePolicy(sizePolicy)
        self.listWidget.setMinimumSize(QSize(200, 0))
        self.listWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.listWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # add to grid
        self.grid = QGridLayout(self.wg)
        self.grid.addWidget(self.folderButton_up,0,0,1,1)
        self.grid.addWidget(self.folderButton,0,1,1,1)
        self.grid.addWidget(self.listWidget, 2, 0, 1, 2)
        # actions
        self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
        self.connect(self.folderButton_up, SIGNAL("clicked()"),self.on_folderButton_up_clicked)
        self.connect(self.folderButton, SIGNAL("clicked()"),self.on_folderButton_clicked)
        self.connect(self.listWidget, SIGNAL("itemClicked(QListWidgetItem *)"), self.on_listWidget_itemClicked)

        # set initial path
        path = os.path.dirname(globals()['alarmfilePicker'].valueText())
        if not os.path.isdir(path):
            path = "/home/user/MyDocs/"
        fileInfo = QFileInfo(path)
        self.folderButton.setText( fileInfo.fileName() )
        if path == "/":
            self.folderButton.setText( "/" )
            self.folderButton.setValueText( "" )
        self.FillBrowser(path)
        self.wg.show()

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() < screenGeometry.height():
            # portrait
            self.wg.resize(398, 692)

    def FillBrowser (self,Directory):
        global hPath
        hPath = Directory
        if hPath == "/":
            self.folderButton_up.setDisabled(True)
        else:
            self.folderButton_up.setDisabled(False)
        self.folderButton.setText( QFileInfo(Directory).fileName() )
        self.folderButton.setValueText(Directory)
        if Directory == "/":
            self.folderButton.setText("/")
            self.folderButton.setValueText("")
        self.listWidget.clear()

        # sort dirs/files case-insensitive
        dirs = sorted([d for d in os.listdir(Directory) if os.path.isdir(Directory + os.path.sep + d)])
        dirs.sort(key=lambda y: y.lower())
        filelist = sorted([f for f in os.listdir(Directory) if os.path.isfile(Directory + os.path.sep + f)])
        filelist.sort(key=lambda y: y.lower())
        dirs.extend(filelist)

        # add revelant ones to the list
        teller = 0
        audio_ext = ('.mp3','.wav','.ogg')
        for fileName in dirs:
            teller += 1
            f=os.path.join(Directory, fileName)
            if fileName == "." or fileName == "..":
                continue
            elif os.path.isdir(f):
                item1 = QListWidgetItem( self.listWidget )
                item1.setText(fileName)
                if fileName == ".videos":
                    item1.setIcon(QIcon.fromTheme("filemanager_video_folder"))
                elif fileName == ".sounds":
                    item1.setIcon(QIcon.fromTheme("filemanager_audio_folder"))
                elif fileName == "DCIM":
                    item1.setIcon(QIcon.fromTheme("filemanager_camera_folder"))
                elif fileName == ".documents":
                    item1.setIcon(QIcon.fromTheme("filemanager_document_folder"))
                elif fileName == ".images":
                    item1.setIcon(QIcon.fromTheme("filemanager_image_folder"))
                else:
                    item1.setIcon(QIcon.fromTheme("general_folder"))

                self.listWidget.insertItem( teller, item1 )
            elif os.path.isfile(f):
                if fileName.lower().endswith((audio_ext)):
                    item1 = QListWidgetItem( self.listWidget )
                    item1.setText(fileName)
                    item1.setIcon(QIcon.fromTheme("general_audio_file"))
                    self.listWidget.insertItem( teller, item1 )

        if self.listWidget.count() > 0:
            self.listWidget.scrollToItem(self.listWidget.item(0))

    def on_folderButton_up_clicked(self):
        if  hPath == "/":
            return
        nPath = os.path.dirname(os.path.dirname(hPath+'/'))
        if nPath == "":
            nPath = "/"
            self.folderButton_up.setDisabled(True)
        else:
            self.folderButton_up.setDisabled(False)
        self.FillBrowser( nPath )

    def on_listWidget_itemClicked(self,item):
        temp = hPath
        if temp != "/":
            temp = temp + "/"
        temp =temp + item.text()

        if os.path.isfile(temp):
            globals()['alarmfilePicker'].setValueText(temp)
            self.wg.close()
        elif os.path.isdir(temp):
            self.FillBrowser(temp)

    def on_folderButton_clicked(self):
        widget = folderWindow(self)
        widget.show()

    def on_folderButton2_clicked(self):
        self.FillBrowser( "/opt/cooktimer/alarmsounds" )

    def on_folderButton1_clicked(self):
        self.FillBrowser( "/home/user/MyDocs" )

    def on_folderButton3_clicked(self):
        self.FillBrowser( "/" )

class folderWindow(QWidget):
    def __init__(self,parent):
        super(folderWindow, self).__init__(parent)
        self.wg = QDialog(self)
        #self.wg.resize(392, 692)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.wg.sizePolicy().hasHeightForWidth())
        self.wg.setSizePolicy(sizePolicy)
        self.wg.setWindowTitle(self.tr("Select folder"))
        # folders display
        self.folderButton1 = QMaemo5ValueButton(self.wg)
        self.folderButton1.setIcon(QIcon.fromTheme("general_folder"))
        self.folderButton1.setText( "MyDocs" )
        self.folderButton1.setValueText( "/home/user/MyDocs" )
        self.folderButton1.setMinimumSize(QSize(0,70))
        self.folderButton2 = QMaemo5ValueButton(self.wg)
        self.folderButton2.setIcon(QIcon.fromTheme("general_folder"))
        self.folderButton2.setText( "alarmsounds" )
        self.folderButton2.setValueText( "/opt/cooktimer/alarmsounds" )
        self.folderButton2.setMinimumSize(QSize(0,70))
        self.folderButton3 = QMaemo5ValueButton(self.wg)
        self.folderButton3.setIcon(QIcon.fromTheme("general_folder"))
        self.folderButton3.setText( "root" )
        self.folderButton3.setValueText( "/" )
        self.folderButton3.setMinimumSize(QSize(0,70))
        # add to grid
        self.grid = QGridLayout(self.wg)
        self.grid.addWidget(self.folderButton1,0,0,1,1)
        self.grid.addWidget(self.folderButton2,1,0,1,1)
        self.grid.addWidget(self.folderButton3,2,0,1,1)
        # actions
        self.connect(self.folderButton1, SIGNAL("clicked()"),parent.on_folderButton1_clicked)
        self.connect(self.folderButton1, SIGNAL("clicked()"),self.wg.close)
        self.connect(self.folderButton2, SIGNAL("clicked()"),parent.on_folderButton2_clicked)
        self.connect(self.folderButton2, SIGNAL("clicked()"),self.wg.close)
        self.connect(self.folderButton3, SIGNAL("clicked()"),parent.on_folderButton3_clicked)
        self.connect(self.folderButton3, SIGNAL("clicked()"),self.wg.close)
        # show
        self.wg.show()

class FormWidget(QWidget):
    def __init__(self, parent):
        super(FormWidget, self).__init__(parent)
        global dishName1banner
        global dishName2banner
        global dishName3banner
        global hoursPicked1
        global minutesPicked1
        global secondsPicked1
        global hoursPicked2
        global minutesPicked2
        global secondsPicked2
        global hoursPicked3
        global minutesPicked3
        global secondsPicked3
        global hoursPicked1saved
        global minutesPicked1saved
        global secondsPicked1saved
        global hoursPicked2saved
        global minutesPicked2saved
        global secondsPicked2saved
        global hoursPicked3saved
        global minutesPicked3saved
        global secondsPicked3saved
        global isContinueMode1
        global isContinueMode1Restore
        global isContinueMode1Active
        global isStopwatchMode1
        global isContinueMode2
        global isContinueMode2Restore
        global isContinueMode2Active
        global isStopwatchMode2
        global isContinueMode3
        global isContinueMode3Restore
        global isContinueMode3Active
        global isStopwatchMode3
        global msgTxtPicked1_1, msgTimePicked1_1, msgTxtPicked1_2, msgTimePicked1_2, msgTxtPicked1_3, msgTimePicked1_3
        global msgTxtPicked2_1, msgTimePicked2_1, msgTxtPicked2_2, msgTimePicked2_2, msgTxtPicked2_3, msgTimePicked2_3
        global msgTxtPicked3_1, msgTimePicked3_1, msgTxtPicked3_2, msgTimePicked3_2, msgTxtPicked3_3, msgTimePicked3_3

        # Timer1
        self.Timer1 = QTimer()
        self.Timer1.timeout.connect(self.updateTimer1)
        # Timer2
        self.Timer2 = QTimer()
        self.Timer2.timeout.connect(self.updateTimer2)
        # Timer3
        self.Timer3 = QTimer()
        self.Timer3.timeout.connect(self.updateTimer3)

        font = QFont()
        font.setPointSize(48)
        startTime= QTime(0, 0, 0)

        self.gerechtButton1 = QPushButton(self.tr("Choose dish"))
        self.gerechtButton2 = QPushButton(self.tr("Choose dish"))
        self.gerechtButton3 = QPushButton(self.tr("Choose dish"))
        self.timeButton1 = QPushButton("00:00:00")
        self.timeButton2 = QPushButton("00:00:00")
        self.timeButton3 = QPushButton("00:00:00")
        file = codecs.open(Cooktimer_Start,"r", encoding="utf-8")
        data = file.readlines()
        file.close()
        f = codecs.open(Cooktimer_ItemFile,"r", encoding="utf-8")
        lines = f.readlines()
        f.close()
        rewriteFile = False
        for count in range(0,3):
            foundInItems = False
            if not data[count].split("|")[0] == "Choose dish":
                for count2 in range(0,len(lines)):
                    if  data[count].split("|")[0] == lines[count2].split("|")[0]:
                        foundInItems = True
                if not foundInItems:
                    rewriteFile = True
                    # orphaned dish, remove it
                    data[count] = "Choose dish|0|0\n"
        if rewriteFile:
            file = codecs.open(Cooktimer_Start,"w", encoding="utf-8")
            data = "".join(data)
            file.write(data)
            file.close()
        file = codecs.open(Cooktimer_Start,"r", encoding="utf-8")
        data = file.readlines()
        file.close()
        f = codecs.open(Cooktimer_ItemFile,"r", encoding="utf-8")
        lines = f.readlines()
        f.close()
        for count in range(0,3):
            data[count] = data[count].strip()
            for count2 in range(0,len(lines)):
                if  data[count].split("|")[0] == lines[count2].split("|")[0]:
                    if count == 0:
                        lines[count2] = lines[count2].strip()
                        for count3 in range(lines[count2].count('|'),7):
                            lines[count2] = lines[count2] + "|"
                        (dishName1banner, timestring, msgTxtPicked1_1, msgTimePicked1_1, msgTxtPicked1_2, msgTimePicked1_2, msgTxtPicked1_3, msgTimePicked1_3) = lines[count2].split('|')
                        if dishName1banner == "Choose dish":
                            self.gerechtButton1.setText(self.tr("Choose dish"))
                        else: self.gerechtButton1.setText(dishName1banner)
                        self.timeButton1.setText(timestring)
                    if count == 1:
                        lines[count2] = lines[count2].strip()
                        for count3 in range(lines[count2].count('|'),7):
                            lines[count2] = lines[count2] + "|"
                        (dishName2banner, timestring, msgTxtPicked2_1, msgTimePicked2_1, msgTxtPicked2_2, msgTimePicked2_2, msgTxtPicked2_3, msgTimePicked2_3) = lines[count2].split('|')
                        if dishName2banner == "Choose dish":
                            self.gerechtButton2.setText(self.tr("Choose dish"))
                        else: self.gerechtButton2.setText(dishName2banner)
                        self.timeButton2.setText(timestring)
                    if count == 2:
                        lines[count2] = lines[count2].strip()
                        for count3 in range(lines[count2].count('|'),7):
                            lines[count2] = lines[count2] + "|"
                        (dishName3banner, timestring, msgTxtPicked3_1, msgTimePicked3_1, msgTxtPicked3_2, msgTimePicked3_2, msgTxtPicked3_3, msgTimePicked3_3) = lines[count2].split('|')
                        if dishName3banner == "Choose dish":
                            self.gerechtButton3.setText(self.tr("Choose dish"))
                        else: self.gerechtButton3.setText(dishName3banner)
                        self.timeButton3.setText(timestring)
        (dummy, c, s) = data[0].split('|')
        if c == "1":
            isContinueMode1 = True
        if s == "1":
            isStopwatchMode1 = True
        (dummy, c, s) = data[1].split('|')
        if c == "1":
            isContinueMode2 = True
        if s == "1":
            isStopwatchMode2 = True
        (dummy, c, s) = data[2].split('|')
        if c == "1":
            isContinueMode3 = True
        if s == "1":
            isStopwatchMode3 = True
        self.initDishText = self.tr("Choose dish")
        # set initial time
        self.timeRemaining1 = QPushButton("00:00:00")
        self.timeRemaining2 = QPushButton("00:00:00")
        self.timeRemaining3 = QPushButton("00:00:00")
        # set font
        self.timeRemaining1.setFont(font)
        self.timeRemaining2.setFont(font)
        self.timeRemaining3.setFont(font)
        # set start text
        self.startButton1 = QPushButton(self.tr('Start'))
        self.startButton2 = QPushButton(self.tr('Start'))
        self.startButton3 = QPushButton(self.tr('Start'))
        # set stylesheets
        self.defaultButtonColorGrey = "QPushButton {" \
            "border: 1px solid #676B67;" \
            "border-radius: 6px;" \
            "background-color: #3A3B3A;" \
            "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, " \
                "stop: 0 #676967, stop: 1 #3A3B3A);" \
            "}" \
            "QPushButton:pressed {" \
            "border: 1px solid #333333;" \
            "background-color: #222222;" \
            "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, " \
                "stop: 0 #444444, stop: 1 #222222);" \
        "}"
        self.defaultButtonColorGreen = "QPushButton {" \
            "border: 1px solid #199909;" \
            "border-radius: 6px;" \
            "background-color: #116a06;" \
            "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, " \
            "stop: 0 #22c70d, stop: 1 #116a06);" \
            "}" \
            "QPushButton:pressed {" \
            "border: 1px solid #234F1D;" \
            "background-color: #143A0F;" \
            "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, " \
            "stop: 0 #3A8930, stop: 1 #163C11);" \
            "}"
        self.defaultButtonColorRed = "QPushButton {" \
                "border: 1px solid #E81F11;" \
                "border-radius: 6px;" \
                "background-color: #95211B;" \
                "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, " \
                "stop: 0 #FF1410, stop: 1 #95211B);" \
                "}" \
                "QPushButton:pressed {" \
                "border: 1px solid #A54841;" \
                "background-color: #502623;" \
                "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.67, " \
                "stop: 0 #A12927, stop: 1 #571F1C);" \
                "}"
        self.orangeTimeRemain = "QPushButton { background : #FF6600; color : white; border-width: 1px; \
                           border-color: #FD9A59 ; border-radius: 9px; border-style: outset; }"
        self.redTimeRemain = "QPushButton { background : #8A0808; color : white; border-width: 1px; \
                           border-color: #AB0E0E ; border-radius: 9px; border-style: outset; }"
        self.greenTimeRemain = "QPushButton { background : #21610B; color : white; border-width: 1px; \
                           border-color: #3E8F23 ; border-radius: 9px; border-style: outset; }"
        self.yellowTimeRemain = "QPushButton { background : #A9881F; color : white; border-width: 1px; \
                                       border-color: #9F9005 ; border-radius: 9px; border-style: outset; }"
        self.darkGreyTimeRemain = "QPushButton { color: #848484; background : #2A2B29; border-width: 1px;\
                           border-color: black ; border-radius: 9px; border-style: inset; }"
        self.darkYellowTimeRemain = "QPushButton { color: #848484; background : #504934; border-width: 1px; \
                           border-color: #504934 ; border-radius: 9px; border-style: inset; }"
        # set stylesheets
        self.timeButton1.setStyleSheet(self.defaultButtonColorGrey)
        self.gerechtButton1.setStyleSheet(self.defaultButtonColorGrey)
        self.timeButton2.setStyleSheet(self.defaultButtonColorGrey)
        self.gerechtButton2.setStyleSheet(self.defaultButtonColorGrey)
        self.timeButton3.setStyleSheet(self.defaultButtonColorGrey)
        self.gerechtButton3.setStyleSheet(self.defaultButtonColorGrey)
        self.timeRemaining1.setStyleSheet(self.darkGreyTimeRemain)
        self.timeRemaining2.setStyleSheet(self.darkGreyTimeRemain)
        self.timeRemaining3.setStyleSheet(self.darkGreyTimeRemain)
        self.startButton1.setStyleSheet(self.defaultButtonColorGrey)
        self.startButton2.setStyleSheet(self.defaultButtonColorGrey)
        self.startButton3.setStyleSheet(self.defaultButtonColorGrey)
        # correct size of buttons
        self.gerechtButton1.setMinimumHeight(65)
        self.gerechtButton1.setMaximumHeight(65)
        self.gerechtButton2.setMinimumHeight(65)
        self.gerechtButton2.setMaximumHeight(65)
        self.gerechtButton3.setMinimumHeight(65)
        self.gerechtButton3.setMaximumHeight(65)
        self.timeButton1.setMinimumHeight(65)
        self.timeButton1.setMaximumHeight(65)
        self.timeButton2.setMinimumHeight(65)
        self.timeButton2.setMaximumHeight(65)
        self.timeButton3.setMinimumHeight(65)
        self.timeButton3.setMaximumHeight(65)
        self.startButton1.setMinimumHeight(65)
        self.startButton1.setMaximumHeight(65)
        self.startButton2.setMinimumHeight(65)
        self.startButton2.setMaximumHeight(65)
        self.startButton3.setMinimumHeight(65)
        self.startButton3.setMaximumHeight(65)
        # add to grid
        grid = QGridLayout()
        grid.addWidget(self.gerechtButton1,0,0)
        grid.addWidget(self.timeButton1,0,1)
        grid.addWidget(self.startButton1,0,2)
        grid.addWidget(self.timeRemaining1,1,0,1,3)
        grid.addWidget(self.gerechtButton2,2,0)
        grid.addWidget(self.timeButton2,2,1)
        grid.addWidget(self.startButton2,2,2)
        grid.addWidget(self.timeRemaining2,3,0,1,3)
        grid.addWidget(self.gerechtButton3,4,0)
        grid.addWidget(self.timeButton3,4,1)
        grid.addWidget(self.startButton3,4,2)
        grid.addWidget(self.timeRemaining3,5,0,1,3)
        if self.gerechtButton1.text() != self.tr("Choose dish"):
            if self.timeButton1.text() != "00:00:00":
                self.startButton1.setStyleSheet(self.defaultButtonColorGreen)
            startTime1 = self.timeButton1.text()
            (hoursPicked1, minutesPicked1, secondsPicked1) = startTime1.split(':')
            hoursPicked1saved = hoursPicked1
            minutesPicked1saved = minutesPicked1
            secondsPicked1saved = secondsPicked1
            if not isStopwatchMode1:
                self.timeRemaining1.setStyleSheet(self.darkGreyTimeRemain)
                self.timeRemaining1.setText(self.timeButton1.text())
        if isContinueMode1 and not isStopwatchMode1:
            self.timeRemaining1.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
        if isStopwatchMode1:
            self.timeRemaining1.setStyleSheet(self.darkYellowTimeRemain)
            self.timeRemaining1.setText("00:00:00")
            isContinueMode1Restore = isContinueMode1
            isContinueMode1 = False
            self.startButton1.setStyleSheet(self.defaultButtonColorGreen)
        if self.gerechtButton2.text() != self.tr("Choose dish"):
            if self.timeButton2.text() != "00:00:00":
                self.startButton2.setStyleSheet(self.defaultButtonColorGreen)
            startTime2 = self.timeButton2.text()
            (hoursPicked2, minutesPicked2, secondsPicked2) = startTime2.split(':')
            hoursPicked2saved = hoursPicked2
            minutesPicked2saved = minutesPicked2
            secondsPicked2saved = secondsPicked2
            if not isStopwatchMode2:
                self.timeRemaining2.setStyleSheet(self.darkGreyTimeRemain)
                self.timeRemaining2.setText(self.timeButton2.text())
        if isContinueMode2 and not isStopwatchMode2:
            self.timeRemaining2.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
        if isStopwatchMode2:
            self.timeRemaining2.setStyleSheet(self.darkYellowTimeRemain)
            self.timeRemaining2.setText("00:00:00")
            isContinueMode2Restore = isContinueMode2
            isContinueMode2 = False
            self.startButton2.setStyleSheet(self.defaultButtonColorGreen)
        if self.gerechtButton3.text() != self.tr("Choose dish"):
            if self.timeButton3.text() != "00:00:00":
                self.startButton3.setStyleSheet(self.defaultButtonColorGreen)
            startTime3 = self.timeButton1.text()
            (hoursPicked3, minutesPicked3, secondsPicked3) = startTime3.split(':')
            hoursPicked3saved = hoursPicked3
            minutesPicked3saved = minutesPicked3
            secondsPicked3saved = secondsPicked3
            if not isStopwatchMode3:
                self.timeRemaining3.setStyleSheet(self.darkGreyTimeRemain)
                self.timeRemaining3.setText(self.timeButton3.text())
        if isContinueMode3 and not isStopwatchMode3:
            self.timeRemaining3.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
        if isStopwatchMode3:
            self.timeRemaining3.setStyleSheet(self.darkYellowTimeRemain)
            self.timeRemaining3.setText("00:00:00")
            isContinueMode3Restore = isContinueMode3
            isContinueMode3 = False
            self.startButton3.setStyleSheet(self.defaultButtonColorGreen)
        # set minimum column width for time and start button
        grid.setColumnMinimumWidth(1, 120)
        grid.setColumnMinimumWidth(2, 120)

        self.timeRemaining1.setAutoRepeat(True)
        self.timeRemaining1.setAutoRepeatDelay(1000)
        self.timeRemaining1.setAutoRepeatInterval(1000)
        self.timeRemaining2.setAutoRepeat(True)
        self.timeRemaining2.setAutoRepeatDelay(1000)
        self.timeRemaining2.setAutoRepeatInterval(1000)
        self.timeRemaining3.setAutoRepeat(True)
        self.timeRemaining3.setAutoRepeatDelay(1000)
        self.timeRemaining3.setAutoRepeatInterval(1000)
        self.timeButton1.setAutoRepeat(True)
        self.timeButton1.setAutoRepeatDelay(1000)
        self.timeButton1.setAutoRepeatInterval(1000)
        self.timeButton2.setAutoRepeat(True)
        self.timeButton2.setAutoRepeatDelay(1000)
        self.timeButton2.setAutoRepeatInterval(1000)
        self.timeButton3.setAutoRepeat(True)
        self.timeButton3.setAutoRepeatDelay(1000)
        self.timeButton3.setAutoRepeatInterval(1000)
        self.gerechtButton1.setAutoRepeat(True)
        self.gerechtButton1.setAutoRepeatDelay(1000)
        self.gerechtButton1.setAutoRepeatInterval(1000)
        self.gerechtButton2.setAutoRepeat(True)
        self.gerechtButton2.setAutoRepeatDelay(1000)
        self.gerechtButton2.setAutoRepeatInterval(1000)
        self.gerechtButton3.setAutoRepeat(True)
        self.gerechtButton3.setAutoRepeatDelay(1000)
        self.gerechtButton3.setAutoRepeatInterval(1000)
        self.startButton1.setAutoRepeat(True)
        self.startButton1.setAutoRepeatDelay(1000)
        self.startButton1.setAutoRepeatInterval(1000)
        self.startButton2.setAutoRepeat(True)
        self.startButton2.setAutoRepeatDelay(1000)
        self.startButton2.setAutoRepeatInterval(1000)
        self.startButton3.setAutoRepeat(True)
        self.startButton3.setAutoRepeatDelay(1000)
        self.startButton3.setAutoRepeatInterval(1000)
        # Let's make something happen when the button is pushed!
        self.startButton1.clicked.connect(self.startButtonClicked1)
        self.startButton2.clicked.connect(self.startButtonClicked2)
        self.startButton3.clicked.connect(self.startButtonClicked3)
        self.gerechtButton1.clicked.connect(self.gerechtButtonClicked1)
        self.gerechtButton2.clicked.connect(self.gerechtButtonClicked2)
        self.gerechtButton3.clicked.connect(self.gerechtButtonClicked3)
        self.timeButton1.clicked.connect(self.pickedTimeClicked1)
        self.timeButton2.clicked.connect(self.pickedTimeClicked2)
        self.timeButton3.clicked.connect(self.pickedTimeClicked3)
        self.timeRemaining1.clicked.connect(self.timeClicked1)
        self.timeRemaining2.clicked.connect(self.timeClicked2)
        self.timeRemaining3.clicked.connect(self.timeClicked3)
        self._state1 = 0
        self._state2 = 0
        self._state3 = 0

        # Set the layout on the window: this means that our button will actually be displayed.
        self.setLayout(grid)

    def timeClicked1(self):
        global isContinueMode1
        global isStopwatchMode1
        global isContinueMode1Restore
        global isContinueMode1Active
        global pause1
        if self.timeRemaining1.isDown():
            if self._state1 == 0:
                self._state1 = 1
                if not self.Timer1.isActive() and not pause1:
                    isStopwatchMode1 = not isStopwatchMode1
                    self.Timer1.stop()
                    pause1 = False
                    if isStopwatchMode1:
                        stopwatchMsg = self.tr("Stopwatch mode ON")
                        # dark yellow
                        self.timeRemaining1.setStyleSheet(self.darkYellowTimeRemain)
                        self.timeRemaining1.setText("00:00:00")
                        self.timeRemaining1.setIcon(QIcon(""))
                        isContinueMode1Restore = isContinueMode1
                        isContinueMode1 = False
                        isContinueMode1Active = False
                        self.startButton1.setText(self.tr('Start'))
                        self.startButton1.setStyleSheet(self.defaultButtonColorGreen)
                    else:
                        # dark grey
                        self.timeRemaining1.setStyleSheet(self.darkGreyTimeRemain)
                        self.timeRemaining1.setText(self.timeButton1.text())
                        if isContinueMode1Restore:
                            isContinueMode1 = True
                            self.timeRemaining1.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                            stopwatchMsg = self.tr("Continue mode ON")
                        else:
                            stopwatchMsg = self.tr("Stopwatch mode OFF")
                        self.startButton1.setText(self.tr('Start'))
                        if self.timeButton1.text() == "00:00:00":
                            self.startButton1.setStyleSheet(self.defaultButtonColorGrey)
                        else:
                            # green
                            self.startButton1.setStyleSheet(self.defaultButtonColorGreen)
                    os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                        /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                        string:"'+stopwatchMsg+'"')
        elif self._state1 == 1:
            self._state1 = 0
        else:
            self.togglePause1()

    def timeClicked2(self):
        global isContinueMode2
        global isStopwatchMode2
        global isContinueMode2Restore
        global isContinueMode2Active
        global pause2
        if self.timeRemaining2.isDown():
            if self._state2 == 0:
                self._state2 = 1
                if not self.Timer2.isActive() and not pause2:
                    isStopwatchMode2 = not isStopwatchMode2
                    self.Timer2.stop()
                    pause2 = False
                    if isStopwatchMode2:
                        stopwatchMsg = self.tr("Stopwatch mode ON")
                        # dark yellow
                        self.timeRemaining2.setStyleSheet(self.darkYellowTimeRemain)
                        self.timeRemaining2.setText("00:00:00")
                        self.timeRemaining2.setIcon(QIcon(""))
                        isContinueMode2Restore = isContinueMode2
                        isContinueMode2 = False
                        isContinueMode2Active = False
                        self.startButton2.setText(self.tr('Start'))
                        self.startButton2.setStyleSheet(self.defaultButtonColorGreen)
                    else:
                        # dark grey
                        self.timeRemaining2.setStyleSheet(self.darkGreyTimeRemain)
                        self.timeRemaining2.setText(self.timeButton2.text())
                        if isContinueMode2Restore:
                            isContinueMode2 = True
                            self.timeRemaining2.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                            stopwatchMsg = self.tr("Continue mode ON")
                        else:
                            stopwatchMsg = self.tr("Stopwatch mode OFF")
                        self.startButton2.setText(self.tr('Start'))
                        if self.timeButton2.text() == "00:00:00":
                            self.startButton2.setStyleSheet(self.defaultButtonColorGrey)
                        else:
                            # green
                            self.startButton2.setStyleSheet(self.defaultButtonColorGreen)
                    os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                        /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                        string:"'+stopwatchMsg+'"')
        elif self._state2 == 1:
            self._state2 = 0
        else:
            self.togglePause2()

    def timeClicked3(self):
        global isContinueMode3
        global isStopwatchMode3
        global pause3
        global isContinueMode3Active
        global isContinueMode3Restore
        if self.timeRemaining3.isDown():
            if self._state3 == 0:
                self._state3 = 1
                if not self.Timer3.isActive() and not pause3:
                    isStopwatchMode3 = not isStopwatchMode3
                    self.Timer3.stop()
                    pause3 = False
                    if isStopwatchMode3:
                        stopwatchMsg = self.tr("Stopwatch mode ON")
                        # dark yellow
                        self.timeRemaining3.setStyleSheet(self.darkYellowTimeRemain)
                        self.timeRemaining3.setText("00:00:00")
                        self.timeRemaining3.setIcon(QIcon(""))
                        isContinueMode3Restore = isContinueMode3
                        isContinueMode3 = False
                        isContinueMode3Active = False
                        self.startButton3.setText(self.tr('Start'))
                        self.startButton3.setStyleSheet(self.defaultButtonColorGreen)
                    else:
                        # dark grey
                        self.timeRemaining3.setStyleSheet(self.darkGreyTimeRemain)
                        self.timeRemaining3.setText(self.timeButton3.text())
                        if isContinueMode3Restore:
                            isContinueMode3 = True
                            self.timeRemaining3.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                            stopwatchMsg = self.tr("Continue mode ON")
                        else:
                            stopwatchMsg = self.tr("Stopwatch mode OFF")
                        self.startButton3.setText(self.tr('Start'))
                        if self.timeButton3.text() == "00:00:00":
                            self.startButton3.setStyleSheet(self.defaultButtonColorGrey)
                        else:
                            # green
                            self.startButton3.setStyleSheet(self.defaultButtonColorGreen)
                    os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                        /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                        string:"'+stopwatchMsg+'"')
        elif self._state3 == 1:
            self._state3 = 0
        else:
            self.togglePause3()

    def pickedTimeClicked1(self):
        global isStopwatchMode1
        global secondsPicked1
        global minutesPicked1
        global hoursPicked1
        global isContinueMode1
        global isContinueMode1Active
        global isContinueMode1Restore
        global pause1
        if self.timeButton1.isDown():
            if self._state1 == 0:
                self._state1 = 1
                if not isContinueMode1Active and not isStopwatchMode1:
                    isContinueMode1 = not isContinueMode1
                    if isContinueMode1:
                        stopwatchMsg = self.tr("Continue mode ON")
                        if self.timeRemaining1.styleSheet() == (self.darkGreyTimeRemain):
                            self.timeRemaining1.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                        else:
                            self.timeRemaining1.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_white.png"))
                        if pause1:
                            self.timeRemaining1.setText("-"+self.timeRemaining1.text())
                    else:
                        stopwatchMsg = self.tr("Continue mode OFF")
                        self.timeRemaining1.setIcon(QIcon(""))
                        if pause1:
                            self.timeRemaining1.setText(self.timeRemaining1.text()[1:])
                    os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                        /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                        string:"'+stopwatchMsg+'"')
            #else:
            #   print 'repeat'
        elif self._state1 == 1:
            self._state1 = 0
        else:
            self.setPickedTime1()

    def pickedTimeClicked2(self):
        global isStopwatchMode2
        global secondsPicked2
        global minutesPicked2
        global hoursPicked2
        global isContinueMode2
        global isContinueMode2Active
        global isContinueMode2Restore
        global pause2
        if self.timeButton2.isDown():
            if self._state2 == 0:
                self._state2 = 1
                if not isContinueMode2Active and not isStopwatchMode2:
                    isContinueMode2 = not isContinueMode2
                    if isContinueMode2:
                        stopwatchMsg = self.tr("Continue mode ON")
                        if self.timeRemaining2.styleSheet() == (self.darkGreyTimeRemain):
                            self.timeRemaining2.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                        else:
                            self.timeRemaining2.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_white.png"))
                        if pause2:
                            self.timeRemaining2.setText("-"+self.timeRemaining2.text())
                    else:
                        stopwatchMsg = self.tr("Continue mode OFF")
                        self.timeRemaining2.setIcon(QIcon(""))
                        if pause2:
                            self.timeRemaining2.setText(self.timeRemaining2.text()[1:])
                    os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                        /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                        string:"'+stopwatchMsg+'"')
            #else:
            #   print 'repeat'
        elif self._state2 == 1:
            self._state2 = 0
        else:
            self.setPickedTime2()

    def pickedTimeClicked3(self):
        global isStopwatchMode3
        global secondsPicked3
        global minutesPicked3
        global hoursPicked3
        global isContinueMode3
        global isContinueMode3Active
        global isContinueMode3Restore
        global pause3
        if self.timeButton3.isDown():
            if self._state3 == 0:
                self._state3 = 1
                if not isContinueMode3Active and not isStopwatchMode3:
                    isContinueMode3 = not isContinueMode3
                    if isContinueMode3:
                        stopwatchMsg = self.tr("Continue mode ON")
                        if self.timeRemaining3.styleSheet() == (self.darkGreyTimeRemain):
                            self.timeRemaining3.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                        else:
                            self.timeRemaining3.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_white.png"))
                        if pause3:
                            self.timeRemaining3.setText("-"+self.timeRemaining3.text())
                    else:
                        stopwatchMsg = self.tr("Continue mode OFF")
                        self.timeRemaining3.setIcon(QIcon(""))
                        if pause3:
                            self.timeRemaining3.setText(self.timeRemaining3.text()[1:])
                    os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                        /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                        string:"'+stopwatchMsg+'"')
            #else:
            #   print 'repeat'
        elif self._state3 == 1:
            self._state3 = 0
        else:
            self.setPickedTime3()


    def gerechtButtonClicked1(self):
        global secondsPicked1saved
        global minutesPicked1saved
        global hoursPicked1saved
        global secondsPicked1
        global minutesPicked1
        global hoursPicked1
        global dishName1
        global dishName1banner
        global currSelector
        global msgTxtPicked1_1
        global msgTimePicked1_1
        global msgTxtPicked1_2
        global msgTimePicked1_2
        global msgTxtPicked1_3
        global msgTimePicked1_3
        global isStopwatchMode1
        global isContinueMode1
        global isContinueMode1Active
        global pause1
        global notesFile
        if self.gerechtButton1.isDown():
            if dishName1banner:
                self.dialog = QDialog(self)
                self.dialog.setWindowTitle(dishName1banner)

                layoutScrolling = QGridLayout()
                layoutScrolling.setAlignment(Qt.AlignTop)
                widgetScrolling = QWidget()
                widgetScrolling.setLayout(layoutScrolling)

                areaScrolling = QScrollArea()
                areaScrolling.setWidget(widgetScrolling)
                areaScrolling.setWidgetResizable(True)

                layoutDialog = QVBoxLayout()
                self.dialog.setLayout(layoutDialog)
                layoutDialog.addWidget(areaScrolling,0)

                notesFile = Cooktimer_NotesDir + dishName1banner + ".txt"

                # interim messages display
                hours = '%02d'  % int(hoursPicked1saved)
                minutes = '%02d'  % int(minutesPicked1saved)
                seconds = '%02d'  % int(secondsPicked1saved)
                msgAlarmTime = QLabel(hours+":"+minutes+":"+seconds)
                msgAlarmTime.setMaximumWidth(100)
                if ( int(hoursPicked1) == int(hoursPicked1saved) and int(minutesPicked1) == int(minutesPicked1saved) and int(secondsPicked1) == int(secondsPicked1saved) ):
                    msgAlarmTxt = QLabel(self.tr("Cooking time"))
                else:
                    msgAlarmTxt = QLabel(self.tr("Cooking time")+"\xc2\xa0".decode('utf-8')+"\xc2\xa0".decode('utf-8')+"("+self.tr("Timer changed")+"!)")
                layoutScrolling.addWidget(msgAlarmTime,0,0)
                layoutScrolling.addWidget(msgAlarmTxt,0,1)
                if msgTimePicked1_1:
                    msg1Time = QLabel(msgTimePicked1_1)
                    msg1Txt = QLabel(msgTxtPicked1_1)
                    layoutScrolling.addWidget(msg1Time,1,0)
                    layoutScrolling.addWidget(msg1Txt,1,1)
                if msgTimePicked1_2:
                    msg2Time = QLabel(msgTimePicked1_2)
                    msg2Txt = QLabel(msgTxtPicked1_2)
                    layoutScrolling.addWidget(msg2Time,2,0)
                    layoutScrolling.addWidget(msg2Txt,2,1)
                if msgTimePicked1_3:
                    msg3Time = QLabel(msgTimePicked1_3)
                    msg3Txt = QLabel(msgTxtPicked1_3)
                    layoutScrolling.addWidget(msg3Time,3,0)
                    layoutScrolling.addWidget(msg3Txt,3,1)
                if not ( msgTimePicked1_1 or msgTimePicked1_2 or msgTimePicked1_3 ):
                    msg0 = QLabel(self.tr("No interim messages"))
                    layoutScrolling.addWidget(msg0,1,0,1,2)
                if os.path.isfile(notesFile):
                    file = codecs.open(notesFile,"r", encoding="utf-8")
                    notes = QLabel("\n" + file.read())
                    file.close()
                    layoutScrolling.addWidget(notes,4,0,1,2)
                self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
                self.dialog.show()
                self.orientationChanged()
            if self._state1 == 0:
                self._state1 = 1
                self.gerechtButton1.setAutoRepeat(False)
        elif self._state1 == 1:
            self._state1 = 0
            self.gerechtButton1.setAutoRepeat(True)
        else:
            currSelector = 1
            dishPick = DishPickDialog(self)
            dishPick.show()
            if dishName1:
                self.gerechtButton1.setText(dishName1)
                dish_items = load_dishes(self)
                (hoursPicked1, minutesPicked1, secondsPicked1) = dish_items[dishPicked1Nbr][1][:8].split(':')
                hours = '%02d' % int(hoursPicked1)
                minutes = '%02d' % int(minutesPicked1)
                seconds = '%02d' % int(secondsPicked1)
                hoursPicked1saved = hours
                minutesPicked1saved = minutes
                secondsPicked1saved = seconds
                timestring = hours + ":" + minutes + ":" + seconds
                self.timeButton1.setText(timestring)
                xtrInfo = dish_items[dishPicked1Nbr][1]
                # | = 0: no extra info 6: all extra messages used
                for count in range(xtrInfo.count('|'),6):
                    # add |, make sure all can be read
                    xtrInfo = xtrInfo + "|"
                (dummy, msgTxtPicked1_1, msgTimePicked1_1, msgTxtPicked1_2, msgTimePicked1_2, msgTxtPicked1_3, msgTimePicked1_3) = xtrInfo.split('|')

                if not self.Timer1.isActive() and not pause1 and not isStopwatchMode1:
                    self.timeRemaining1.setText(timestring)
                    if timestring == "00:00:00":
                        self.startButton1.setStyleSheet(self.defaultButtonColorGrey)
                    else:
                        self.startButton1.setStyleSheet(self.defaultButtonColorGreen)
                # clear it again
                dishName1banner = dishName1
                dishName1 = ""

    def gerechtButtonClicked2(self):
        global secondsPicked2saved
        global minutesPicked2saved
        global hoursPicked2saved
        global secondsPicked2
        global minutesPicked2
        global hoursPicked2
        global dishName2
        global dishName2banner
        global currSelector
        global msgTxtPicked2_1
        global msgTimePicked2_1
        global msgTxtPicked2_2
        global msgTimePicked2_2
        global msgTxtPicked2_3
        global msgTimePicked2_3
        global isStopwatchMode2
        global isContinueMode2
        global isContinueMode2Active
        global pause2
        if self.gerechtButton2.isDown():
            if dishName2banner:
                self.dialog = QDialog(self)
                self.dialog.setWindowTitle(dishName2banner)

                layoutScrolling = QGridLayout()
                layoutScrolling.setAlignment(Qt.AlignTop)
                widgetScrolling = QWidget()
                widgetScrolling.setLayout(layoutScrolling)

                areaScrolling = QScrollArea()
                areaScrolling.setWidget(widgetScrolling)
                areaScrolling.setWidgetResizable(True)

                layoutDialog = QVBoxLayout()
                self.dialog.setLayout(layoutDialog)
                layoutDialog.addWidget(areaScrolling,0)

                notesFile = Cooktimer_NotesDir + dishName2banner + ".txt"

                # interim messages display
                hours = '%02d'  % int(hoursPicked2saved)
                minutes = '%02d'  % int(minutesPicked2saved)
                seconds = '%02d'  % int(secondsPicked2saved)
                msgAlarmTime = QLabel(hours+":"+minutes+":"+seconds)
                msgAlarmTime.setMaximumWidth(100)
                if ( int(hoursPicked2) == int(hoursPicked2saved) and int(minutesPicked2) == int(minutesPicked2saved) and int(secondsPicked2) == int(secondsPicked2saved) ):
                    msgAlarmTxt = QLabel(self.tr("Cooking time"))
                else:
                    msgAlarmTxt = QLabel(self.tr("Cooking time")+"\xc2\xa0".decode('utf-8')+"\xc2\xa0".decode('utf-8')+"("+self.tr("Timer changed")+"!)")
                layoutScrolling.addWidget(msgAlarmTime,0,0)
                layoutScrolling.addWidget(msgAlarmTxt,0,1)
                if msgTimePicked2_1:
                    msg1Time = QLabel(msgTimePicked2_1)
                    msg1Txt = QLabel(msgTxtPicked2_1)
                    layoutScrolling.addWidget(msg1Time,1,0)
                    layoutScrolling.addWidget(msg1Txt,1,1)
                if msgTimePicked2_2:
                    msg2Time = QLabel(msgTimePicked2_2)
                    msg2Txt = QLabel(msgTxtPicked2_2)
                    layoutScrolling.addWidget(msg2Time,2,0)
                    layoutScrolling.addWidget(msg2Txt,2,1)
                if msgTimePicked2_3:
                    msg3Time = QLabel(msgTimePicked2_3)
                    msg3Txt = QLabel(msgTxtPicked2_3)
                    layoutScrolling.addWidget(msg3Time,3,0)
                    layoutScrolling.addWidget(msg3Txt,3,1)
                if not ( msgTimePicked2_1 or msgTimePicked2_2 or msgTimePicked2_3 ):
                    msg0 = QLabel(self.tr("No interim messages"))
                    layoutScrolling.addWidget(msg0,1,0,1,2)
                if os.path.isfile(notesFile):
                    file = codecs.open(notesFile,"r", encoding="utf-8")
                    notes = QLabel("\n" + file.read())
                    file.close()
                    layoutScrolling.addWidget(notes,4,0,1,2)
                self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
                self.dialog.show()
                self.orientationChanged()
            if self._state2 == 0:
                self._state2 = 1
                self.gerechtButton2.setAutoRepeat(False)
        elif self._state2 == 1:
            self._state2 = 0
            self.gerechtButton2.setAutoRepeat(True)
        else:
            currSelector = 2
            dishPick = DishPickDialog(self)
            dishPick.show()
            if dishName2:
                self.gerechtButton2.setText(dishName2)
                dish_items = load_dishes(self)
                (hoursPicked2, minutesPicked2, secondsPicked2) = dish_items[dishPicked2Nbr][1][:8].split(':')
                hours = '%02d' % int(hoursPicked2)
                minutes = '%02d' % int(minutesPicked2)
                seconds = '%02d' % int(secondsPicked2)
                hoursPicked2saved = hours
                minutesPicked2saved = minutes
                secondsPicked2saved = seconds
                timestring = hours + ":" + minutes + ":" + seconds
                self.timeButton2.setText(timestring)

                xtrInfo = dish_items[dishPicked2Nbr][1]
                # | = 0: no extra info 6: all extra messages used
                for count in range(xtrInfo.count('|'),6):
                    # add |, make sure all can be read
                    xtrInfo = xtrInfo + "|"
                (dummy, msgTxtPicked2_1, msgTimePicked2_1, msgTxtPicked2_2, msgTimePicked2_2, msgTxtPicked2_3, msgTimePicked2_3) = xtrInfo.split('|')

                if not self.Timer2.isActive() and not pause2 and not isStopwatchMode2:
                    self.timeRemaining2.setText(timestring)
                    if timestring == "00:00:00":
                        self.startButton2.setStyleSheet(self.defaultButtonColorGrey)
                    else:
                        self.startButton2.setStyleSheet(self.defaultButtonColorGreen)
                # clear it again
                dishName2banner = dishName2
                dishName2 = ""

    def gerechtButtonClicked3(self):
        global secondsPicked3saved
        global minutesPicked3saved
        global hoursPicked3saved
        global secondsPicked3
        global minutesPicked3
        global hoursPicked3
        global dishName3
        global dishName3banner
        global currSelector
        global msgTxtPicked3_1
        global msgTimePicked3_1
        global msgTxtPicked3_2
        global msgTimePicked3_2
        global msgTxtPicked3_3
        global msgTimePicked3_3
        global isStopwatchMode3
        global isContinueMode3
        global isContinueMode3Active
        global pause3
        if self.gerechtButton3.isDown():
            if dishName3banner:
                self.dialog = QDialog(self)
                self.dialog.setWindowTitle(dishName3banner)

                layoutScrolling = QGridLayout()
                layoutScrolling.setAlignment(Qt.AlignTop)
                widgetScrolling = QWidget()
                widgetScrolling.setLayout(layoutScrolling)

                areaScrolling = QScrollArea()
                areaScrolling.setWidget(widgetScrolling)
                areaScrolling.setWidgetResizable(True)

                layoutDialog = QVBoxLayout()
                self.dialog.setLayout(layoutDialog)
                layoutDialog.addWidget(areaScrolling,0)

                notesFile = Cooktimer_NotesDir + dishName3banner + ".txt"

                # interim messages display
                hours = '%02d'  % int(hoursPicked3saved)
                minutes = '%02d'  % int(minutesPicked3saved)
                seconds = '%02d'  % int(secondsPicked3saved)
                msgAlarmTime = QLabel(hours+":"+minutes+":"+seconds)
                msgAlarmTime.setMaximumWidth(100)
                if ( int(hoursPicked3) == int(hoursPicked3saved) and int(minutesPicked3) == int(minutesPicked3saved) and int(secondsPicked3) == int(secondsPicked3saved) ):
                    msgAlarmTxt = QLabel(self.tr("Cooking time"))
                else:
                    msgAlarmTxt = QLabel(self.tr("Cooking time")+"\xc2\xa0".decode('utf-8')+"\xc2\xa0".decode('utf-8')+"("+self.tr("Timer changed")+"!)")
                layoutScrolling.addWidget(msgAlarmTime,0,0)
                layoutScrolling.addWidget(msgAlarmTxt,0,1)
                if msgTimePicked3_1:
                    msg1Time = QLabel(msgTimePicked3_1)
                    msg1Txt = QLabel(msgTxtPicked3_1)
                    layoutScrolling.addWidget(msg1Time,1,0)
                    layoutScrolling.addWidget(msg1Txt,1,1)
                if msgTimePicked3_2:
                    msg2Time = QLabel(msgTimePicked3_2)
                    msg2Txt = QLabel(msgTxtPicked3_2)
                    layoutScrolling.addWidget(msg2Time,2,0)
                    layoutScrolling.addWidget(msg2Txt,2,1)
                if msgTimePicked3_3:
                    msg3Time = QLabel(msgTimePicked3_3)
                    msg3Txt = QLabel(msgTxtPicked3_3)
                    layoutScrolling.addWidget(msg3Time,3,0)
                    layoutScrolling.addWidget(msg3Txt,3,1)
                if not ( msgTimePicked3_1 or msgTimePicked3_2 or msgTimePicked3_3 ):
                    msg0 = QLabel(self.tr("No interim messages"))
                    layoutScrolling.addWidget(msg0,1,0,1,2)
                if os.path.isfile(notesFile):
                    file = codecs.open(notesFile,"r", encoding="utf-8")
                    notes = QLabel("\n" + file.read())
                    file.close()
                    layoutScrolling.addWidget(notes,4,0,1,2)
                self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
                self.dialog.show()
                self.orientationChanged()
            if self._state3 == 0:
                self._state3 = 1
                self.gerechtButton3.setAutoRepeat(False)
        elif self._state3 == 1:
            self._state3 = 0
            self.gerechtButton3.setAutoRepeat(True)
        else:
            currSelector = 3
            dishPick = DishPickDialog(self)
            dishPick.show()
            if dishName3:
                self.gerechtButton3.setText(dishName3)
                dish_items = load_dishes(self)
                (hoursPicked3, minutesPicked3, secondsPicked3) = dish_items[dishPicked3Nbr][1][:8].split(':')
                hours = '%02d' % int(hoursPicked3)
                minutes = '%02d' % int(minutesPicked3)
                seconds = '%02d' % int(secondsPicked3)
                hoursPicked3saved = hours
                minutesPicked3saved = minutes
                secondsPicked3saved = seconds
                timestring = hours + ":" + minutes + ":" + seconds
                self.timeButton3.setText(timestring)

                xtrInfo = dish_items[dishPicked3Nbr][1]
                # | = 0: no extra info 6: all extra messages used
                for count in range(xtrInfo.count('|'),6):
                    # add |, make sure all can be read
                    xtrInfo = xtrInfo + "|"
                (dummy, msgTxtPicked3_1, msgTimePicked3_1, msgTxtPicked3_2, msgTimePicked3_2, msgTxtPicked3_3, msgTimePicked3_3) = xtrInfo.split('|')

                if not self.Timer3.isActive() and not pause3 and not isStopwatchMode3:
                    self.timeRemaining3.setText(timestring)
                    if timestring == "00:00:00":
                        self.startButton3.setStyleSheet(self.defaultButtonColorGrey)
                    else:
                        self.startButton3.setStyleSheet(self.defaultButtonColorGreen)
                # clear it again
                dishName3banner = dishName3
                dishName3 = ""

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        self.dialog.adjustSize()
        if (screenGeometry.width() > screenGeometry.height() and self.dialog.height() > 310):
            # landscape
            self.dialog.resize(800, 378)
        if (screenGeometry.width() < screenGeometry.height() and self.dialog.height() > 530):
            # portrait
            self.dialog.resize(480, 698)

    def startButtonClicked1(self):
        global secondsPicked1
        global minutesPicked1
        global hoursPicked1
        global isContinueMode1Active
        global isContinueMode1
        global pause1
        global currTimer
        if self.startButton1.isDown():
            currTimer = 1
            tm = QDialog(self)
            tm.setWindowTitle(self.tr("Timer 1"))
            vbox = QVBoxLayout()
            tm.setLayout(vbox)
            # options display
            timeroptionReset = QPushButton(self.tr("Reset"),self)
            timeroptionSetonStart = QPushButton(self.tr("Startup settings"),self)
            vbox.addWidget(timeroptionReset,0)
            vbox.addWidget(timeroptionSetonStart,1)
            # actions
            timeroptionReset.clicked.connect(self.TimerReset1)
            timeroptionReset.clicked.connect(tm.close)
            timeroptionSetonStart.clicked.connect(self.TimerSetonStart)
            timeroptionSetonStart.clicked.connect(tm.close)
            tm.show()
            if self._state1 == 0:
                self._state1 = 1
                self.startButton1.setAutoRepeat(False)
        elif self._state1 == 1:
            self._state1 = 0
            self.startButton1.setAutoRepeat(True)
        else:
        # remark: indented 1 tab to end of "def" code section
            if not isStopwatchMode1:
                startTime1 = str('%02d'  % int(hoursPicked1)) + ":" + str('%02d' % int(minutesPicked1)) + ":" + str('%02d' % int(secondsPicked1))
            else:
                startTime1 = self.timeRemaining1.text()
            if self.Timer1.isActive() or pause1:
                self.Timer1.stop()
                if not isStopwatchMode1:
                    self.timeRemaining1.setText(self.timeButton1.text())
                    if isContinueMode1:
                        self.timeRemaining1.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                else:
                    self.timeRemaining1.setText("00:00:00")
                isContinueMode1Active = False
                pause1 = False
                self.startButton1.setText(self.tr('Start'))
                self.startButton1.setStyleSheet(self.defaultButtonColorGreen)
                if isStopwatchMode1:
                    # dark yellow
                    self.timeRemaining1.setStyleSheet(self.darkYellowTimeRemain)
                else:
                    # dark grey
                    self.timeRemaining1.setStyleSheet(self.darkGreyTimeRemain)
                if startTime1 == "00:00:00" and not isStopwatchMode1:
                    self.startButton1.setStyleSheet(self.defaultButtonColorGrey)
            else:
                if startTime1 != "00:00:00" or isStopwatchMode1:
                    if not isStopwatchMode1:
                        self.timeRemaining1.setText(self.timeButton1.text())
                    self.Timer1.start(1000)
                    (h, m, s) = startTime1.split(':')
                    self.startSecs1 = int(h) * 3600 + int(m) * 60 + int(s)
                    if not isStopwatchMode1:
                        # green
                        self.timeRemaining1.setStyleSheet(self.greenTimeRemain)
                        if isContinueMode1:
                            self.timeRemaining1.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_white.png"))
                    else:
                        # yellow
                        self.timeRemaining1.setStyleSheet(self.yellowTimeRemain)
                    self.startButton1.setText(self.tr("Stop"))
                    self.startButton1.setStyleSheet(self.defaultButtonColorRed)

    def TimerReset1(self):
        global secondsPicked1
        global minutesPicked1
        global hoursPicked1
        global secondsPicked1saved
        global minutesPicked1saved
        global hoursPicked1saved
        global dishName1
        global dishName1banner
        global msgTxtPicked1_1
        global msgTimePicked1_1
        global msgTxtPicked1_2
        global msgTimePicked1_2
        global msgTxtPicked1_3
        global msgTimePicked1_3
        global isStopwatchMode1
        global isContinueMode1
        global isContinueMode1Active
        global pause1
        self.timeRemaining1.setText("00:00:00")
        self.timeButton1.setText("00:00:00")
        (hoursPicked1, minutesPicked1, secondsPicked1) = "00:00:00".split(':')
        hoursPicked1saved = ""
        minutesPicked1saved = ""
        secondsPicked1saved = ""
        isStopwatchMode1 = False
        isContinueMode1 = False
        isContinueMode1Active = False
        msgTxtPicked1_1 = ""
        msgTimePicked1_1 = ""
        msgTxtPicked1_2 = ""
        msgTimePicked1_2 = ""
        msgTxtPicked1_3 = ""
        msgTimePicked1_3 = ""
        dishName1 = ""
        dishName1banner = ""
        self.timeRemaining1.setIcon(QIcon(""))
        self.startButton1.setText(self.tr('Start'))
        self.gerechtButton1.setText(self.tr("Choose dish"))
        self.Timer1.stop()
        pause1 = False
        # dark grey
        self.timeRemaining1.setStyleSheet(self.darkGreyTimeRemain)
        self.startButton1.setStyleSheet(self.defaultButtonColorGrey)

    def startButtonClicked2(self):
        global secondsPicked2
        global minutesPicked2
        global hoursPicked2
        global isContinueMode2Active
        global isContinueMode2
        global pause2
        global currTimer
        if self.startButton2.isDown():
            currTimer = 2
            tm = QDialog(self)
            tm.setWindowTitle(self.tr("Timer 2"))
            vbox = QVBoxLayout()
            tm.setLayout(vbox)
            # options display
            timeroptionReset = QPushButton(self.tr("Reset"),self)
            timeroptionSetonStart = QPushButton(self.tr("Startup settings"),self)
            vbox.addWidget(timeroptionReset,0)
            vbox.addWidget(timeroptionSetonStart,1)
            # actions
            timeroptionReset.clicked.connect(self.TimerReset2)
            timeroptionReset.clicked.connect(tm.close)
            timeroptionSetonStart.clicked.connect(self.TimerSetonStart)
            timeroptionSetonStart.clicked.connect(tm.close)
            tm.show()
            if self._state2 == 0:
                self._state2 = 1
                self.startButton2.setAutoRepeat(False)
        elif self._state2 == 1:
            self._state2 = 0
            self.startButton2.setAutoRepeat(True)
        else:
        # remark: indented 1 tab to end of "def" code section
            if not isStopwatchMode2:
                startTime2 = str('%02d'  % int(hoursPicked2)) + ":" + str('%02d' % int(minutesPicked2)) + ":" + str('%02d' % int(secondsPicked2))
            else:
                startTime2 = self.timeRemaining2.text()
            if self.Timer2.isActive() or pause2:
                self.Timer2.stop()
                if not isStopwatchMode2:
                    self.timeRemaining2.setText(self.timeButton2.text())
                    if isContinueMode2:
                        self.timeRemaining2.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                else:
                    self.timeRemaining2.setText("00:00:00")
                isContinueMode2Active = False
                pause2 = False
                self.startButton2.setText(self.tr('Start'))
                self.startButton2.setStyleSheet(self.defaultButtonColorGreen)
                if isStopwatchMode2:
                    # dark yellow
                    self.timeRemaining2.setStyleSheet(self.darkYellowTimeRemain)
                else:
                    # dark grey
                    self.timeRemaining2.setStyleSheet(self.darkGreyTimeRemain)
                if startTime2 == "00:00:00" and not isStopwatchMode2:
                    self.startButton2.setStyleSheet(self.defaultButtonColorGrey)
            else:
                if startTime2 != "00:00:00" or isStopwatchMode2:
                    if not isStopwatchMode2:
                        self.timeRemaining2.setText(self.timeButton2.text())
                    self.Timer2.start(1000)
                    (h, m, s) = startTime2.split(':')
                    self.startSecs2 = int(h) * 3600 + int(m) * 60 + int(s)
                    if not isStopwatchMode2:
                        # green
                        self.timeRemaining2.setStyleSheet(self.greenTimeRemain)
                        if isContinueMode2:
                            self.timeRemaining2.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_white.png"))
                    else:
                        # yellow
                        self.timeRemaining2.setStyleSheet(self.yellowTimeRemain)
                    self.startButton2.setText(self.tr("Stop"))
                    self.startButton2.setStyleSheet(self.defaultButtonColorRed)

    def TimerReset2(self):
        global secondsPicked2
        global minutesPicked2
        global hoursPicked2
        global secondsPicked2saved
        global minutesPicked2saved
        global hoursPicked2saved
        global dishName2
        global dishName2banner
        global msgTxtPicked2_1
        global msgTimePicked2_1
        global msgTxtPicked2_2
        global msgTimePicked2_2
        global msgTxtPicked2_3
        global msgTimePicked2_3
        global isStopwatchMode2
        global isContinueMode2
        global isContinueMode2Active
        global pause2
        self.timeRemaining2.setText("00:00:00")
        self.timeButton2.setText("00:00:00")
        (hoursPicked2, minutesPicked2, secondsPicked2) = "00:00:00".split(':')
        hoursPicked2saved = ""
        minutesPicked2saved = ""
        secondsPicked2saved = ""
        isStopwatchMode2 = False
        isContinueMode2 = False
        isContinueMode2Active = False
        msgTxtPicked2_1 = ""
        msgTimePicked2_1 = ""
        msgTxtPicked2_2 = ""
        msgTimePicked2_2 = ""
        msgTxtPicked2_3 = ""
        msgTimePicked2_3 = ""
        dishName2 = ""
        dishName2banner = ""
        self.timeRemaining2.setIcon(QIcon(""))
        self.startButton2.setText(self.tr('Start'))
        self.gerechtButton2.setText(self.tr("Choose dish"))
        self.Timer2.stop()
        pause2 = False
        # dark grey
        self.timeRemaining2.setStyleSheet(self.darkGreyTimeRemain)
        self.startButton2.setStyleSheet(self.defaultButtonColorGrey)

    def startButtonClicked3(self):
        global secondsPicked3
        global minutesPicked3
        global hoursPicked3
        global isContinueMode3Active
        global isContinueMode3
        global pause3
        global currTimer
        if self.startButton3.isDown():
            currTimer = 3
            tm = QDialog(self)
            tm.setWindowTitle(self.tr("Timer 3"))
            vbox = QVBoxLayout()
            tm.setLayout(vbox)
            # options display
            timeroptionReset = QPushButton(self.tr("Reset"),self)
            timeroptionSetonStart = QPushButton(self.tr("Startup settings"),self)
            vbox.addWidget(timeroptionReset,0)
            vbox.addWidget(timeroptionSetonStart,1)
            # actions
            timeroptionReset.clicked.connect(self.TimerReset3)
            timeroptionReset.clicked.connect(tm.close)
            timeroptionSetonStart.clicked.connect(self.TimerSetonStart)
            timeroptionSetonStart.clicked.connect(tm.close)
            tm.show()
            if self._state3 == 0:
                self._state3 = 1
                self.startButton3.setAutoRepeat(False)
        elif self._state3 == 1:
            self._state3 = 0
            self.startButton3.setAutoRepeat(True)
        else:
        # remark: indented 1 tab to end of "def" code section
            if not isStopwatchMode3:
                startTime3 = str('%02d'  % int(hoursPicked3)) + ":" + str('%02d' % int(minutesPicked3)) + ":" + str('%02d' % int(secondsPicked3))
            else:
                startTime3 = self.timeRemaining3.text()
            if self.Timer3.isActive() or pause3:
                self.Timer3.stop()
                if not isStopwatchMode3:
                    self.timeRemaining3.setText(self.timeButton3.text())
                    if isContinueMode3:
                        self.timeRemaining3.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_grey.png"))
                else:
                    self.timeRemaining3.setText("00:00:00")
                isContinueMode3Active = False
                pause3 = False
                self.startButton3.setText(self.tr('Start'))
                self.startButton3.setStyleSheet(self.defaultButtonColorGreen)
                if isStopwatchMode3:
                    # dark yellow
                    self.timeRemaining3.setStyleSheet(self.darkYellowTimeRemain)
                else:
                    # dark grey
                    self.timeRemaining3.setStyleSheet(self.darkGreyTimeRemain)
                if startTime3 == "00:00:00" and not isStopwatchMode3:
                    self.startButton3.setStyleSheet(self.defaultButtonColorGrey)
            else:
                if startTime3 != "00:00:00" or isStopwatchMode3:
                    if not isStopwatchMode3:
                        self.timeRemaining3.setText(self.timeButton3.text())
                    self.Timer3.start(1000)
                    (h, m, s) = startTime3.split(':')
                    self.startSecs3 = int(h) * 3600 + int(m) * 60 + int(s)
                    if not isStopwatchMode3:
                        # green
                        self.timeRemaining3.setStyleSheet(self.greenTimeRemain)
                        if isContinueMode3:
                            self.timeRemaining3.setIcon(QIcon("/opt/cooktimer/icons/continue_mode_white.png"))
                    else:
                        # yellow
                        self.timeRemaining3.setStyleSheet(self.yellowTimeRemain)
                    self.startButton3.setText(self.tr("Stop"))
                    self.startButton3.setStyleSheet(self.defaultButtonColorRed)

    def TimerReset3(self):
        global secondsPicked3
        global minutesPicked3
        global hoursPicked3
        global secondsPicked3saved
        global minutesPicked3saved
        global hoursPicked3saved
        global dishName3
        global dishName3banner
        global msgTxtPicked3_1
        global msgTimePicked3_1
        global msgTxtPicked3_2
        global msgTimePicked3_2
        global msgTxtPicked3_3
        global msgTimePicked3_3
        global isStopwatchMode3
        global isContinueMode3
        global isContinueMode3Active
        global pause3
        self.timeRemaining3.setText("00:00:00")
        self.timeButton3.setText("00:00:00")
        (hoursPicked3, minutesPicked3, secondsPicked3) = "00:00:00".split(':')
        hoursPicked3saved = ""
        minutesPicked3saved = ""
        secondsPicked3saved = ""
        isStopwatchMode3 = False
        isContinueMode3 = False
        isContinueMode3Active = False
        msgTxtPicked3_1 = ""
        msgTimePicked3_1 = ""
        msgTxtPicked3_2 = ""
        msgTimePicked3_2 = ""
        msgTxtPicked3_3 = ""
        msgTimePicked3_3 = ""
        dishName3 = ""
        dishName3banner = ""
        self.timeRemaining3.setIcon(QIcon(""))
        self.startButton3.setText(self.tr('Start'))
        self.gerechtButton3.setText(self.tr("Choose dish"))
        self.Timer3.stop()
        pause2 = False
        # dark grey
        self.timeRemaining3.setStyleSheet(self.darkGreyTimeRemain)
        self.startButton3.setStyleSheet(self.defaultButtonColorGrey)

    def TimerSetonStart(self):
        global currTimer
        self.dialog = QDialog(self)
        self.dialog.setWindowTitle(self.tr("Timer") + " " + str(currTimer) + self.tr(" startup settings"))
        self.layoutDialog = QGridLayout()
        self.dialog.setLayout(self.layoutDialog)

        widgetOptions = QWidget()
        layoutOptions = QGridLayout()
        widgetOptions.setLayout(layoutOptions)

        # options display
        self.timerSetDish = QMaemo5ValueButton(self.tr("Dish"),self)
        self.timerSetDish.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
        self.timerSetCmode = QCheckBox(self.tr("Continue mode"),self)
        self.timerSetSmode = QCheckBox(self.tr("Stopwatch mode"),self)
        timerSetonStartReset = QPushButton("",self)
        timerSetonStartReset.setIcon(QIcon.fromTheme("general_delete"))
        timerSetonStartReset.setMaximumWidth(48)
        timerSetonStartReset.setStyleSheet("background: transparent; border: none")
        self.timerSetonStartDone = QPushButton(self.tr("Done"),self)
        layoutOptions.addWidget(self.timerSetDish,0,0)
        layoutOptions.addWidget(timerSetonStartReset,0,1)
        layoutOptions.addWidget(self.timerSetCmode,1,0)
        layoutOptions.addWidget(self.timerSetSmode,2,0)
        self.layoutDialog.addWidget(widgetOptions,0,0)
        file = codecs.open(Cooktimer_Start,"r", encoding="utf-8")
        data = file.readlines()
        file.close()
        data[currTimer-1] = data[currTimer-1].strip()
        (d,c,s) = data[currTimer-1].split('|')
        if d == "Choose dish":
            self.timerSetDish.setValueText(self.tr("Choose dish"))
        else:
            self.timerSetDish.setValueText(d)
        if c == "1":
            self.timerSetCmode.setChecked(True)
        if s == "1":
            self.timerSetSmode.setChecked(True)
        # actions
        self.timerSetDish.clicked.connect(self.TimerPickDish)
        timerSetonStartReset.clicked.connect(self.TimerSetonStartReset)
        self.timerSetonStartDone.clicked.connect(self.TimerSetonStartDone)
        self.timerSetonStartDone.clicked.connect(self.dialog.close)
        self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.timerDialogOrientationChanged)
        self.dialog.show()
        self.timerDialogOrientationChanged()

    def timerDialogOrientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
            # landscape
            self.layoutDialog.removeWidget(self.timerSetonStartDone)
            self.timerSetonStartDone.setMaximumWidth(160)
            self.layoutDialog.addWidget(self.timerSetonStartDone,0,1,Qt.AlignBottom)
            self.dialog.adjustSize()
        else:
            # portrait
            self.layoutDialog.removeWidget(self.timerSetonStartDone)
            self.timerSetonStartDone.setMaximumWidth(480)
            self.layoutDialog.addWidget(self.timerSetonStartDone,1,0)
            self.dialog.adjustSize()

    def TimerSetonStartReset(self):
        self.timerSetDish.setValueText(self.tr("Choose dish"))
        #self.timerSetCmode.setChecked(False)
        #self.timerSetSmode.setChecked(False)

    def TimerPickDish(self):
        global dishName
        global currSelector
        currSelector = 0
        dishPick = DishPickDialog(self)
        dishPick.show()
        if dishName:
            self.timerSetDish.setValueText(dishName)

    def TimerSetonStartDone(self):
        global currTimer
        file = codecs.open(Cooktimer_Start,"r", encoding="utf-8")
        data = file.readlines()
        file.close()
        d = self.timerSetDish.valueText()
        if d == self.tr("Choose dish"):
            d = "Choose dish"
        if self.timerSetCmode.isChecked():
            c = "1"
        else:
            c = "0"
        if self.timerSetSmode.isChecked():
            s = "1"
        else:
            s = "0"
        if currTimer == 1:
            data = d+"|"+c+"|"+s+"\n"+data[1]+data[2]
        if currTimer == 2:
            data = data[0]+d+"|"+c+"|"+s+"\n"+data[2]
        if currTimer == 3:
            data = data[0]+data[1]+d+"|"+c+"|"+s+"\n"
        file = codecs.open(Cooktimer_Start,"w", encoding="utf-8")
        file.write(data)
        file.close()
        saveMsg = self.tr("Timer "+str(currTimer)+" startup settings are successfully saved")
        os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
            /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
            string:"'+saveMsg+'"')

    def updateTimer1(self):
        global dishName1banner
        global isContinueMode1Active
        global isStopwatchMode1
        if isContinueMode1Active or isStopwatchMode1:
            self.startSecs1 +=1
        else:
            self.startSecs1 -=1
        hhmmss_format=format_seconds_to_hhmmss(self.startSecs1)
        self.timeRemaining1.setText(hhmmss_format)
        if not isContinueMode1Active and not isStopwatchMode1:
            # act on sub actions
            if msgTimePicked1_1 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 1] " + dishName1banner, msgTxtPicked1_1, [], {}, 0)
            if msgTimePicked1_2 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 1] " + dishName1banner, msgTxtPicked1_2, [], {}, 0)
            if msgTimePicked1_3 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 1] " + dishName1banner, msgTxtPicked1_3, [], {}, 0)

            if self.startSecs1 == 0:
                self.Timer1.stop()

                if not pause2:
                    if self.Timer2.isActive():
                        if isContinueMode2Active or isStopwatchMode2:
                            # yellow
                            self.timeRemaining2.setStyleSheet(self.yellowTimeRemain)
                        else:
                            # green
                            self.timeRemaining2.setStyleSheet(self.greenTimeRemain)
                    else:
                        if isStopwatchMode2:
                            # dark yellow
                            self.timeRemaining2.setStyleSheet(self.darkYellowTimeRemain)
                        else:
                            # dark grey
                            self.timeRemaining2.setStyleSheet(self.darkGreyTimeRemain)
                if not pause3:
                    if self.Timer3.isActive():
                        if isContinueMode3Active or isStopwatchMode3:
                            # yellow
                            self.timeRemaining3.setStyleSheet(self.yellowTimeRemain)
                        else:
                            # green
                            self.timeRemaining3.setStyleSheet(self.greenTimeRemain)
                    else:
                        if isStopwatchMode3:
                            # dark yellow
                            self.timeRemaining3.setStyleSheet(self.darkYellowTimeRemain)
                        else:
                            # dark grey
                            self.timeRemaining3.setStyleSheet(self.darkGreyTimeRemain)
                if dishName1banner == "":
                    dishName1banner = "Timer 1"
                if Alarmbanner:
                    printMsg(self,"<h4>" + self.tr("timer 1 ready!") + "</h4><h2>" + dishName1banner + "</h2>",10000)
                Alarm(self)
                if isContinueMode1:
                    isContinueMode1Active = True
                    # yellow
                    self.timeRemaining1.setStyleSheet(self.yellowTimeRemain)
                    self.Timer1.start()
                else:
                    # red
                    self.timeRemaining1.setStyleSheet(self.redTimeRemain)
                    self.startButton1.setText(self.tr("Start"))
                    self.startButton1.setStyleSheet(self.defaultButtonColorGreen)

    def updateTimer2(self):
        global dishName2banner
        global isContinueMode2Active
        global isStopwatchMode2
        if isContinueMode2Active or isStopwatchMode2:
            self.startSecs2 +=1
        else:
            self.startSecs2 -=1
        hhmmss_format=format_seconds_to_hhmmss(self.startSecs2)
        self.timeRemaining2.setText(hhmmss_format)
        if not isContinueMode2Active and not isStopwatchMode2:
            # act on sub actions
            if msgTimePicked2_1 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 2] " + dishName2banner, msgTxtPicked2_1, [], {}, 0)
            if msgTimePicked2_2 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 2] " + dishName2banner, msgTxtPicked2_2, [], {}, 0)
            if msgTimePicked2_3 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 2] " + dishName2banner, msgTxtPicked2_3, [], {}, 0)

            if self.startSecs2 == 0:
                self.Timer2.stop()

                if not pause1:
                    if self.Timer1.isActive():
                        if isContinueMode1Active or isStopwatchMode1:
                            # yellow
                            self.timeRemaining1.setStyleSheet(self.yellowTimeRemain)
                        else:
                            # green
                            self.timeRemaining1.setStyleSheet(self.greenTimeRemain)
                    else:
                        if isStopwatchMode1:
                            # dark yellow
                            self.timeRemaining1.setStyleSheet(self.darkYellowTimeRemain)
                        else:
                            # dark grey
                            self.timeRemaining1.setStyleSheet(self.darkGreyTimeRemain)
                if not pause3:
                    if self.Timer3.isActive():
                        if isContinueMode3Active or isStopwatchMode3:
                            # yellow
                            self.timeRemaining3.setStyleSheet(self.yellowTimeRemain)
                        else:
                            # green
                            self.timeRemaining3.setStyleSheet(self.greenTimeRemain)
                    else:
                        if isStopwatchMode3:
                            # dark yellow
                            self.timeRemaining3.setStyleSheet(self.darkYellowTimeRemain)
                        else:
                            # dark grey
                            self.timeRemaining3.setStyleSheet(self.darkGreyTimeRemain)
                if dishName2banner == "":
                    dishName2banner = "Timer 2"
                if Alarmbanner:
                    printMsg(self,"<h4>" + self.tr("timer 2 ready!") + "</h4><h2>" + dishName2banner + "</h2>",10000)
                Alarm(self)
                if isContinueMode2:
                    isContinueMode2Active = True
                    self.timeRemaining2.setStyleSheet(self.yellowTimeRemain)
                    self.Timer2.start()
                else:
                    # red
                    self.timeRemaining2.setStyleSheet(self.redTimeRemain)
                    self.startButton2.setText(self.tr("Start"))
                    self.startButton2.setStyleSheet(self.defaultButtonColorGreen)

    def updateTimer3(self):
        global dishName3banner
        global isContinueMode3Active
        global isStopwatchMode3
        if isContinueMode3Active or isStopwatchMode3:
            self.startSecs3 +=1
        else:
            self.startSecs3 -=1
        hhmmss_format=format_seconds_to_hhmmss(self.startSecs3)
        self.timeRemaining3.setText(hhmmss_format)
        if not isContinueMode3Active and not isStopwatchMode3:
            # act on sub actions
            if msgTimePicked3_1 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 3] " + dishName3banner, msgTxtPicked3_1, [], {}, 0)
            if msgTimePicked3_2 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 3] " + dishName3banner, msgTxtPicked3_2, [], {}, 0)
            if msgTimePicked3_3 == hhmmss_format:
                Alarm(self)
                bus = dbus.SessionBus()
                proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
                interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')
                interface.Notify('Notification', 0, 'control_bluetooth_paired', "[timer 3] " + dishName3banner, msgTxtPicked3_3, [], {}, 0)

            if self.startSecs3 == 0:
                self.Timer3.stop()

                if not pause1:
                    if self.Timer1.isActive():
                        if isContinueMode1Active or isStopwatchMode1:
                            # yellow
                            self.timeRemaining1.setStyleSheet(self.yellowTimeRemain)
                        else:
                            # green
                            self.timeRemaining1.setStyleSheet(self.greenTimeRemain)
                    else:
                        if isStopwatchMode1:
                            # dark yellow
                            self.timeRemaining1.setStyleSheet(self.darkYellowTimeRemain)
                        else:
                            # dark grey
                            self.timeRemaining1.setStyleSheet(self.darkGreyTimeRemain)
                if not pause2:
                    if self.Timer2.isActive():
                        if isContinueMode2Active or isStopwatchMode2:
                            # yellow
                            self.timeRemaining2.setStyleSheet(self.yellowTimeRemain)
                        else:
                            # green
                            self.timeRemaining2.setStyleSheet(self.greenTimeRemain)
                    else:
                        if isStopwatchMode2:
                            # dark yellow
                            self.timeRemaining2.setStyleSheet(self.darkYellowTimeRemain)
                        else:
                            # dark grey
                            self.timeRemaining2.setStyleSheet(self.darkGreyTimeRemain)
                if dishName3banner == "":
                    dishName3banner = "Timer 3"
                if Alarmbanner:
                    printMsg(self,"<h4>" + self.tr("timer 3 ready!") + "</h4><h2>" + dishName3banner + "</h2>",10000)
                Alarm(self)
                if isContinueMode3:
                    isContinueMode3Active = True
                    self.timeRemaining3.setStyleSheet(self.yellowTimeRemain)
                    self.Timer3.start()
                else:
                    # red
                    self.timeRemaining3.setStyleSheet(self.redTimeRemain)
                    self.startButton3.setText(self.tr("Start"))
                    self.startButton3.setStyleSheet(self.defaultButtonColorGreen)

    def setPickedTime1(self):
        global secondsPicked1
        global minutesPicked1
        global hoursPicked1
        global currSelector
        global pause1
        global dishName1banner
        currSelector = 1
        timePick = TimePickDialog(self)
        timePick.show()
        hours = '%02d' % int(hoursPicked1)
        minutes = '%02d' % int(minutesPicked1)
        seconds = '%02d' % int(secondsPicked1)
        timestring = hours + ":" + minutes + ":" + seconds
        self.timeButton1.setText(timestring)
        if not self.Timer1.isActive() and not pause1 and not isStopwatchMode1:
            self.timeRemaining1.setText(timestring)
            if timestring == "00:00:00":
                self.startButton1.setStyleSheet(self.defaultButtonColorGrey)
            else:
                self.startButton1.setStyleSheet(self.defaultButtonColorGreen)

    def setPickedTime2(self):
        global secondsPicked2
        global minutesPicked2
        global hoursPicked2
        global currSelector
        global pause2
        global dishName2banner
        currSelector = 2
        timePick = TimePickDialog(self)
        timePick.show()
        hours = '%02d' % int(hoursPicked2)
        minutes = '%02d' % int(minutesPicked2)
        seconds = '%02d' % int(secondsPicked2)
        timestring = hours + ":" + minutes + ":" + seconds
        self.timeButton2.setText(timestring)
        if not self.Timer2.isActive() and not pause2 and not isStopwatchMode2:
            self.timeRemaining2.setText(timestring)
            if timestring == "00:00:00":
                self.startButton2.setStyleSheet(self.defaultButtonColorGrey)
            else:
                self.startButton2.setStyleSheet(self.defaultButtonColorGreen)

    def setPickedTime3(self):
        global secondsPicked3
        global minutesPicked3
        global hoursPicked3
        global currSelector
        global pause3
        global dishName3banner
        currSelector = 3
        timePick = TimePickDialog(self)
        timePick.show()
        hours = '%02d' % int(hoursPicked3)
        minutes = '%02d' % int(minutesPicked3)
        seconds = '%02d' % int(secondsPicked3)
        timestring = hours + ":" + minutes + ":" + seconds
        self.timeButton3.setText(timestring)
        if not self.Timer3.isActive() and not pause3 and not isStopwatchMode3:
            self.timeRemaining3.setText(timestring)
            if timestring == "00:00:00":
                self.startButton3.setStyleSheet(self.defaultButtonColorGrey)
            else:
                self.startButton3.setStyleSheet(self.defaultButtonColorGreen)

    def togglePause1(self):
        global pause1
        if self.timeRemaining1.text() != "00:00:00":
            if self.Timer1.isActive():
                self.Timer1.stop()
                self.timeRemaining1.setStyleSheet(self.orangeTimeRemain)
                pause1 = True
                if isContinueMode1Active:
                    self.timeRemaining1.setText("+"+self.timeRemaining1.text())
                if isContinueMode1 and not isContinueMode1Active:
                    self.timeRemaining1.setText("-"+self.timeRemaining1.text())
                if isStopwatchMode1:
                    self.timeRemaining1.setText("+"+self.timeRemaining1.text())
            else:
                if pause1:
                    if isContinueMode1Active or isContinueMode1:
                        # remove leading sign
                        self.timeRemaining1.setText(self.timeRemaining1.text()[1:])
                    if isStopwatchMode1:
                        self.timeRemaining1.setText(self.timeRemaining1.text()[1:])
                    self.Timer1.start()
                    if isContinueMode1Active or isStopwatchMode1:
                        # yellow
                        self.timeRemaining1.setStyleSheet(self.yellowTimeRemain)
                    else:
                        # green
                        self.timeRemaining1.setStyleSheet(self.greenTimeRemain)
                    pause1 = False
        elif Sound:
            Playbin2.set_state(gst.STATE_NULL)  # for gstreamer
            os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
                com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(defaultVolume))
            if playstate == 1:
                os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.resume")

    def togglePause2(self):
        global pause2
        if self.timeRemaining2.text() != "00:00:00":
            if self.Timer2.isActive():
                self.Timer2.stop()
                self.timeRemaining2.setStyleSheet(self.orangeTimeRemain)
                pause2 = True
                if isContinueMode2Active:
                    self.timeRemaining2.setText("+"+self.timeRemaining2.text())
                if isContinueMode2 and not isContinueMode2Active:
                    self.timeRemaining2.setText("-"+self.timeRemaining2.text())
                if isStopwatchMode2:
                    self.timeRemaining2.setText("+"+self.timeRemaining2.text())
            else:
                if pause2:
                    if isContinueMode2Active or isContinueMode2:
                        # remove leading sign
                        self.timeRemaining2.setText(self.timeRemaining2.text()[1:])
                    if isStopwatchMode2:
                        self.timeRemaining2.setText(self.timeRemaining2.text()[1:])
                    self.Timer2.start()
                    if isContinueMode2Active or isStopwatchMode2:
                        # yellow
                        self.timeRemaining2.setStyleSheet(self.yellowTimeRemain)
                    else:
                        # green
                        self.timeRemaining2.setStyleSheet(self.greenTimeRemain)
                    pause2 = False
        elif Sound:
            Playbin2.set_state(gst.STATE_NULL)  # for gstreamer
            os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
                com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(defaultVolume))
            if playstate == 1:
                os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.resume")

    def togglePause3(self):
        global pause3
        if self.timeRemaining3.text() != "00:00:00":
            if self.Timer3.isActive():
                self.Timer3.stop()
                # orange
                self.timeRemaining3.setStyleSheet(self.orangeTimeRemain)
                pause3 = True
                if isContinueMode3Active:
                    self.timeRemaining3.setText("+"+self.timeRemaining3.text())
                if isContinueMode3 and not isContinueMode3Active:
                    self.timeRemaining3.setText("-"+self.timeRemaining3.text())
                if isStopwatchMode3:
                    self.timeRemaining3.setText("+"+self.timeRemaining3.text())
            else:
                if pause3:
                    if isContinueMode3Active or isContinueMode3:
                        # remove leading sign
                        self.timeRemaining3.setText(self.timeRemaining3.text()[1:])
                    if isStopwatchMode3:
                        self.timeRemaining3.setText(self.timeRemaining3.text()[1:])
                    self.Timer3.start()
                    if isContinueMode3Active or isStopwatchMode3:
                        # yellow
                        self.timeRemaining3.setStyleSheet(self.yellowTimeRemain)
                    else:
                        # green
                        self.timeRemaining3.setStyleSheet(self.greenTimeRemain)
                    pause3 = False
        elif Sound:
            Playbin2.set_state(gst.STATE_NULL)  # for gstreamer
            os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
                com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(defaultVolume))
            if playstate == 1:
                os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.resume")

class Gstreamer_play:

    def __init__(self):
        # Setting the pulsesink's event.id to "ringtone-preview". This way, your program gets added
        # to the player group automatically without having to modify xpolicy.conf
        proplist = pa_proplist_new()
        pa_proplist_sets (proplist, "event.id", "ringtone-preview")
        self.pulsesink = gst.element_factory_make("pulsesink", "shit")

        g_object_set(c_void_p(hash(self.pulsesink)), "proplist", proplist, None)
        Playbin2.set_property("audio-sink", self.pulsesink)

        bus = Playbin2.get_bus()
        bus.add_signal_watch()
        bus.connect("message", self.on_message)

    def on_message(self, bus, message):
        t = message.type
        if t == gst.MESSAGE_EOS:
            Playbin2.set_state(gst.STATE_NULL)
            self.playmode = False
            os.system("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer \
                com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(defaultVolume))
            if playstate == 1:
                os.popen("dbus-send --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.renderer.resume")
        elif t == gst.MESSAGE_ERROR:
            Playbin2.set_state(gst.STATE_NULL)
            err, debug = message.parse_error()
            print "Error: %s" % err, debug
            self.playmode = False

    def start(self):
        if os.path.isfile(Alarmfile):
            self.playmode = True
            Playbin2.set_property("uri", "file://" + Alarmfile)
            Playbin2.set_state(gst.STATE_PLAYING)

class TimePickDialog(QWidget):
    def __init__(self,parent):
        super(TimePickDialog, self).__init__(parent)
        self.d = QDialog(self)
        self.d.setMinimumHeight(680)
        self.d.setMaximumHeight(680)
        self.d.setWindowTitle(self.tr("| hours | minutes | seconds |"))
        self.doneButton = QPushButton(self.tr("Done"))
        hbox = QGridLayout()
        self.horizontalLayout = QGridLayout()
        self.hourWidget = QListWidget()
        self.minuteWidget = QListWidget()
        self.secondWidget = QListWidget()
        # performance optimalization in case widget have a uniform size
        self.hourWidget.setUniformItemSizes(True)
        self.minuteWidget.setUniformItemSizes(True)
        self.secondWidget.setUniformItemSizes(True)
        f = QFont()
        f.setPointSize(24)
        global secondsPicked0
        global minutesPicked0
        global hoursPicked0
        global secondsPicked1
        global minutesPicked1
        global hoursPicked1
        global secondsPicked2
        global minutesPicked2
        global hoursPicked2
        global secondsPicked3
        global minutesPicked3
        global hoursPicked3
        global currSelector

        for i in range(49):
            item = QListWidgetItem("%02i" % i)
            item.setFont(f)
            item.setTextAlignment(Qt.AlignCenter)
            self.hourWidget.addItem(item)

        for i in range(60):
            item = QListWidgetItem("%02i" % i)
            item.setFont(f)
            item.setTextAlignment(Qt.AlignCenter)
            self.minuteWidget.addItem(item)

        for i in range(60):
            item = QListWidgetItem("%02i" % i)
            item.setFont(f)
            item.setTextAlignment(Qt.AlignCenter)
            self.secondWidget.addItem(item)

        # set time
        if currSelector == 0:
            self.hourWidget.setCurrentRow(int(hoursPicked0))
            self.minuteWidget.setCurrentRow(int(minutesPicked0))
            self.secondWidget.setCurrentRow(int(secondsPicked0))
        if currSelector == 1:
            self.hourWidget.setCurrentRow(int(hoursPicked1))
            self.minuteWidget.setCurrentRow(int(minutesPicked1))
            self.secondWidget.setCurrentRow(int(secondsPicked1))
        if currSelector == 2:
            self.hourWidget.setCurrentRow(int(hoursPicked2))
            self.minuteWidget.setCurrentRow(int(minutesPicked2))
            self.secondWidget.setCurrentRow(int(secondsPicked2))
        if currSelector == 3:
            self.hourWidget.setCurrentRow(int(hoursPicked3))
            self.minuteWidget.setCurrentRow(int(minutesPicked3))
            self.secondWidget.setCurrentRow(int(secondsPicked3))

        self.horizontalLayout.addWidget(self.hourWidget,0,0)
        self.horizontalLayout.addWidget(self.minuteWidget,0,1)
        self.horizontalLayout.addWidget(self.secondWidget,0,2)
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
            # landscape
            self.horizontalLayout.addWidget(self.doneButton,0,3,Qt.AlignBottom)
            self.doneButton.setMinimumWidth(170)
            self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtTop)
            self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtTop)
            self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtTop)
        else:
            # portrait
            self.horizontalLayout.addWidget(self.doneButton,1,0,1,3)
            self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtCenter)
            self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtCenter)
            self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtCenter)
        self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
        self.d.setLayout(hbox)
        hbox.addLayout (self.horizontalLayout,0,0)
        self.connect(self.doneButton, SIGNAL("clicked()"), self.accept)
        self.d.exec_()

    def accept(self):
        global secondsPicked0
        global minutesPicked0
        global hoursPicked0
        global secondsPicked1
        global minutesPicked1
        global hoursPicked1
        global secondsPicked2
        global minutesPicked2
        global hoursPicked2
        global secondsPicked3
        global minutesPicked3
        global hoursPicked3
        global currSelector
        if currSelector == 0:
            hoursPicked0 = self.hourWidget.currentRow()
            minutesPicked0 = self.minuteWidget.currentRow()
            secondsPicked0 = self.secondWidget.currentRow()
        if currSelector == 1:
            hoursPicked1 = self.hourWidget.currentRow()
            minutesPicked1 = self.minuteWidget.currentRow()
            secondsPicked1 = self.secondWidget.currentRow()
        if currSelector == 2:
            hoursPicked2 = self.hourWidget.currentRow()
            minutesPicked2 = self.minuteWidget.currentRow()
            secondsPicked2 = self.secondWidget.currentRow()
        if currSelector == 3:
            hoursPicked3 = self.hourWidget.currentRow()
            minutesPicked3 = self.minuteWidget.currentRow()
            secondsPicked3 = self.secondWidget.currentRow()
        self.d.close()

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
            # landscape
            self.d.setMinimumHeight(680)
            self.d.setMaximumHeight(680)
            self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtTop)
            self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtTop)
            self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtTop)
            self.horizontalLayout.removeWidget(self.doneButton)
            self.horizontalLayout.addWidget(self.doneButton,0,3,Qt.AlignBottom)
            self.doneButton.setMinimumWidth(170)
        else:
            # portrait
            self.d.resize(680,740)
            self.d.setMinimumHeight(680)
            self.d.setMaximumHeight(680)
            self.hourWidget.scrollToItem(self.hourWidget.currentItem(),QAbstractItemView.PositionAtCenter)
            self.minuteWidget.scrollToItem(self.minuteWidget.currentItem(),QAbstractItemView.PositionAtCenter)
            self.secondWidget.scrollToItem(self.secondWidget.currentItem(),QAbstractItemView.PositionAtCenter)
            self.horizontalLayout.removeWidget(self.doneButton)
            self.horizontalLayout.addWidget(self.doneButton,1,0,1,3)


class DishPickDialog(QWidget):
    def __init__(self,parent):
        super(DishPickDialog, self).__init__(parent)
        self.d = QDialog(self)
        self.d.setMinimumHeight(680)
        self.d.setMaximumHeight(680)
        self.d.setWindowTitle(self.tr("[Choose dish]"))
        hbox = QGridLayout()
        horizontalLayout = QGridLayout()
        self.dishWidget = QListWidget()
        self.dishWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        dish_items = load_dishes(self)
        horizontalLayout.addWidget(self.dishWidget,0,0)

        for gerecht in dish_items:
            item = QListWidgetItem(gerecht[0])
            item.setTextAlignment(Qt.AlignCenter)
            self.dishWidget.addItem(item)
            if currSelector == 1 and dishName1banner == gerecht[0]:
                item.setSelected(True)
                self.dishWidget.setCurrentItem(item)
            if currSelector == 2 and dishName2banner == gerecht[0]:
                item.setSelected(True)
                self.dishWidget.setCurrentItem(item)
            if currSelector == 3 and dishName3banner == gerecht[0]:
                item.setSelected(True)
                self.dishWidget.setCurrentItem(item)

        screenGeometry = QApplication.desktop().screenGeometry()

        self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
        self.d.setLayout(hbox)
        hbox.addLayout (horizontalLayout,0,0)

        self.connect(self.dishWidget, SIGNAL("itemClicked(QListWidgetItem *)"), self.itemClicked)
        self.d.exec_()

    def itemClicked(self, item):
        global currSelector
        global dishName1
        global dishName1banner
        global dishPicked1Nbr
        global dishName2
        global dishPicked2Nbr
        global dishName3
        global dishPicked3Nbr
        global dishName
        if currSelector == 0:
            dishName = item.text()
        if currSelector == 1:
            dishPicked1Nbr = self.dishWidget.currentRow()
            dishName1 = item.text()
        if currSelector == 2:
            dishPicked2Nbr = self.dishWidget.currentRow()
            dishName2 = item.text()
        if currSelector == 3:
            dishPicked3Nbr = self.dishWidget.currentRow()
            dishName3 = item.text()
        self.d.close()

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
            # landscape
            self.d.setMinimumHeight(680)
            self.d.setMaximumHeight(680)
            self.dishWidget.scrollToItem(self.dishWidget.currentItem(),QAbstractItemView.PositionAtTop)
        else:
            # portrait
            self.d.resize(680,740)
            self.d.setMinimumHeight(680)
            self.d.setMaximumHeight(680)
            self.dishWidget.scrollToItem(self.dishWidget.currentItem(),QAbstractItemView.PositionAtCenter)

class editItemWindow(QWidget):
    def __init__(self,parent):
        super(editItemWindow, self).__init__(parent)
        self.dialog = QDialog(self)

        global notesFile
        global rowNbr
        global newdish

        if newdish:
            itemtext = ""
            timetext = "00:00:00"
            self.dialog.setWindowTitle(self.tr("New dish"))
            notesFile = ""
        else:
            itemtext = globals()['Item%s' % rowNbr].text()
            timetext = globals()['Item%s' % rowNbr].valueText()
            self.dialog.setWindowTitle(itemtext)

        layoutScrolling = QGridLayout()
        widgetScrolling = QWidget()
        widgetScrolling.setLayout(layoutScrolling)

        areaScrolling = QScrollArea()
        areaScrolling.setWidget(widgetScrolling)
        areaScrolling.setWidgetResizable(True)

        self.layoutDialog = QGridLayout()
        self.dialog.setLayout(self.layoutDialog)
        self.layoutDialog.addWidget(areaScrolling,0,0)

        self.saveItemButton = QPushButton(self.tr("Done"),self)
        self.saveItemButton.setMinimumWidth(160)

        self.cookItem = QLineEdit(itemtext)
        self.cookHintTxt1 = QLineEdit()
        self.cookHintTxt2 = QLineEdit()
        self.cookHintTxt3 = QLineEdit()
        self.cookItem.setPlaceholderText(self.tr("Dish"))
        self.cookHintTxt1.setPlaceholderText(self.tr("Message"))
        self.cookHintTxt2.setPlaceholderText(self.tr("Message"))
        self.cookHintTxt3.setPlaceholderText(self.tr("Message"))
        layoutScrolling.addWidget(self.cookItem,0,0,1,2)
        layoutScrolling.addWidget(self.cookHintTxt1,1,0,1,2)
        layoutScrolling.addWidget(self.cookHintTxt2,2,0,1,2)
        layoutScrolling.addWidget(self.cookHintTxt3,3,0,1,2)
        self.cooktime = QMaemo5ValueButton(self.tr("time"))
        self.cooktime1 = QMaemo5ValueButton(self.tr("time"))
        self.cooktime2 = QMaemo5ValueButton(self.tr("time"))
        self.cooktime3 = QMaemo5ValueButton(self.tr("time"))
        self.cooktime.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
        self.cooktime1.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
        self.cooktime2.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
        self.cooktime3.setValueLayout(QMaemo5ValueButton.ValueUnderTextCentered)
        self.cooktime.setValueText(timetext)
        self.cooktime1.setValueText("00:00:00")
        self.cooktime2.setValueText("00:00:00")
        self.cooktime3.setValueText("00:00:00")
        layoutScrolling.addWidget(self.cooktime,0,2)
        layoutScrolling.addWidget(self.cooktime1,1,2)
        layoutScrolling.addWidget(self.cooktime2,2,2)
        layoutScrolling.addWidget(self.cooktime3,3,2)
        clearButton1 = QPushButton()
        clearButton1.setMaximumWidth(48)
        clearButton1.setIcon(QIcon.fromTheme("general_delete"))
        clearButton1.setStyleSheet("background: transparent; border: none")
        clearButton2 = QPushButton()
        clearButton2.setIcon(QIcon.fromTheme("general_delete"))
        clearButton2.setStyleSheet("background: transparent; border: none")
        clearButton3 = QPushButton()
        clearButton3.setIcon(QIcon.fromTheme("general_delete"))
        clearButton3.setStyleSheet("background: transparent; border: none")
        layoutScrolling.addWidget(clearButton1,1,3)
        layoutScrolling.addWidget(clearButton2,2,3)
        layoutScrolling.addWidget(clearButton3,3,3)
        labelNotes = QLabel(self.tr("Notes:"))
        layoutScrolling.addWidget(labelNotes,4,0,1,4,Qt.AlignCenter)
        self.cookNotes = QTextEdit()
        self.cookNotes.setMinimumSize(QSize(400, 374))
        self.cookNotes.setMaximumSize(QSize(400, 374))
        self.cookNotes.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        layoutScrolling.addWidget(self.cookNotes,5,0,1,4,Qt.AlignCenter)
        if not newdish:
            notesFile = Cooktimer_NotesDir + self.dialog.windowTitle() + ".txt"
            if os.path.isfile(notesFile):
                try:
                    file = codecs.open(notesFile,"r", encoding="utf-8")
                    self.cookNotes.setText(file.read())
                except:
                    QMessageBox.critical(self, "Warning",  "Cannot read " + self.dialog.windowTitle() + ".txt")
            hh_mi_ss = globals()['Item%s' % rowNbr].valueText().split(':',2)
            allInfo = globals()['Item%s' % rowNbr].statusTip().split('|')
            if len(allInfo) > 1:
                self.cookHintTxt1.setText(allInfo[1])
                self.cooktime1.setValueText(allInfo[2])
            if len(allInfo) > 3:
                self.cookHintTxt2.setText(allInfo[3])
                self.cooktime2.setValueText(allInfo[4])
            if len(allInfo) > 5:
                self.cookHintTxt3.setText(allInfo[5])
                self.cooktime3.setValueText(allInfo[6])

        self.cooktime.clicked.connect(self.TimeSel)
        self.cooktime1.clicked.connect(self.TimeSel1)
        self.cooktime2.clicked.connect(self.TimeSel2)
        self.cooktime3.clicked.connect(self.TimeSel3)
        clearButton1.clicked.connect(self.Clear1)
        clearButton2.clicked.connect(self.Clear2)
        clearButton3.clicked.connect(self.Clear3)
        self.saveItemButton.clicked.connect(self.Saveitems)
        self.connect(QApplication.desktop(), SIGNAL("resized(int)"), self.orientationChanged)
        self.orientationChanged()
        self.dialog.show()

    def orientationChanged(self):
        screenGeometry = QApplication.desktop().screenGeometry()
        if screenGeometry.width() > screenGeometry.height():
            #landscape
            self.dialog.resize(800, 378)
            self.layoutDialog.removeWidget(self.saveItemButton)
            self.layoutDialog.addWidget(self.saveItemButton,0,1,Qt.AlignBottom)
        else:
            #portrait
            self.dialog.resize(480,698)
            self.layoutDialog.removeWidget(self.saveItemButton)
            self.layoutDialog.addWidget(self.saveItemButton,1,0)


    def Clear1(self):
            self.cookHintTxt1.clear()
            self.cooktime1.setValueText("00:00:00")

    def Clear2(self):
            self.cookHintTxt2.clear()
            self.cooktime2.setValueText("00:00:00")

    def Clear3(self):
            self.cookHintTxt3.clear()
            self.cooktime3.setValueText("00:00:00")

    def TimeSel(self):
        global secondsPicked0
        global minutesPicked0
        global hoursPicked0
        global currSelector

        currSelector = 0
        hh_mi_ss = self.cooktime.valueText().split(':',2)
        hoursPicked0 = hh_mi_ss[0]
        minutesPicked0 = hh_mi_ss[1]
        secondsPicked0 = hh_mi_ss[2]

        timePick = TimePickDialog(self)
        timePick.show()
        hours = '%02d' % int(hoursPicked0)
        minutes = '%02d' % int(minutesPicked0)
        seconds = '%02d' % int(secondsPicked0)
        timestring = hours + ":" + minutes + ":" + seconds
        self.cooktime.setValueText(timestring)

    def TimeSel1(self):
        global secondsPicked0
        global minutesPicked0
        global hoursPicked0
        global currSelector

        currSelector = 0
        hh_mi_ss = self.cooktime1.valueText().split(':',2)
        hoursPicked0 = hh_mi_ss[0]
        minutesPicked0 = hh_mi_ss[1]
        secondsPicked0 = hh_mi_ss[2]

        timePick = TimePickDialog(self)
        timePick.show()
        hours = '%02d' % int(hoursPicked0)
        minutes = '%02d' % int(minutesPicked0)
        seconds = '%02d' % int(secondsPicked0)
        timestring = hours + ":" + minutes + ":" + seconds
        self.cooktime1.setValueText(timestring)

    def TimeSel2(self):
        global secondsPicked0
        global minutesPicked0
        global hoursPicked0
        global currSelector

        currSelector = 0
        hh_mi_ss = self.cooktime2.valueText().split(':',2)
        hoursPicked0 = hh_mi_ss[0]
        minutesPicked0 = hh_mi_ss[1]
        secondsPicked0 = hh_mi_ss[2]

        timePick = TimePickDialog(self)
        timePick.show()
        hours = '%02d' % int(hoursPicked0)
        minutes = '%02d' % int(minutesPicked0)
        seconds = '%02d' % int(secondsPicked0)
        timestring = hours + ":" + minutes + ":" + seconds
        self.cooktime2.setValueText(timestring)

    def TimeSel3(self):
        global secondsPicked0
        global minutesPicked0
        global hoursPicked0
        global currSelector

        currSelector = 0
        hh_mi_ss = self.cooktime3.valueText().split(':',2)
        hoursPicked0 = hh_mi_ss[0]
        minutesPicked0 = hh_mi_ss[1]
        secondsPicked0 = hh_mi_ss[2]

        timePick = TimePickDialog(self)
        timePick.show()
        hours = '%02d' % int(hoursPicked0)
        minutes = '%02d' % int(minutesPicked0)
        seconds = '%02d' % int(secondsPicked0)
        timestring = hours + ":" + minutes + ":" + seconds
        self.cooktime3.setValueText(timestring)

    def Saveitems(self):
        global rowNbr
        itemtext = self.cookItem.text().strip()
        if not itemtext:
            msg = self.tr("Dish name is not set!")
            os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                string:"'+msg+'"')
            return
        notesNewFile = Cooktimer_NotesDir + itemtext + ".txt"
        total_time = int(self.cooktime.valueText().replace(":", ""))
        subtime1 = int(self.cooktime1.valueText().replace(":", ""))
        subtime2 = int(self.cooktime2.valueText().replace(":", ""))
        subtime3 = int(self.cooktime3.valueText().replace(":", ""))
        if ( subtime1 >= total_time or subtime2 >= total_time or subtime3 >= total_time ) and total_time:
            msg = self.tr("Message time larger than alarm time!")
            os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                string:"'+msg+'"')
            return
        try:
            file = codecs.open(Cooktimer_ItemFile,"r", encoding="utf-8")
        except:
            QMessageBox.critical(self, "Warning",  "Cannot read " + Cooktimer_ItemFile)
        # read a list of lines into data
        data = file.readlines()
        data.sort(lambda a, b: cmp(a.upper(), b.upper()))
        file.close()
        num_lines = sum(1 for line in open(Cooktimer_ItemFile))
        for count in range(0, num_lines):
            #if (itemtext == data[count].split("|")[0] and (count != rowNbr-1 or newdish)):
            if (itemtext == data[count].split("|")[0] and (itemtext != self.dialog.windowTitle() or newdish)):
                msg = self.tr("Dish name already exists!")
                os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
                /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
                string:"'+msg+'"')
                return
        newLine = itemtext + "|" + self.cooktime.valueText()
        if (self.cooktime1.valueText() != "00:00:00" and self.cookHintTxt1.text() != "" ):
            newLine = newLine + "|" + self.cookHintTxt1.text() + "|" + self.cooktime1.valueText()
        if (self.cooktime2.valueText() != "00:00:00" and self.cookHintTxt2.text() != "" ):
            newLine = newLine + "|" + self.cookHintTxt2.text() + "|" + self.cooktime2.valueText()
        if (self.cooktime3.valueText() != "00:00:00" and self.cookHintTxt3.text() != "" ):
            newLine = newLine + "|" + self.cookHintTxt3.text() + "|" + self.cooktime3.valueText()

        # Dish Info
        if not os.path.exists(Cooktimer_NotesDir):
            try:
                os.mkdir(Cooktimer_NotesDir)
            except:
                QMessageBox.critical(self, "Warning",  "Cannot create " + Cooktimer_NotesDir)
        if os.path.exists(Cooktimer_NotesDir):
            if os.path.isfile(notesFile):
                os.remove(notesFile)
            notes = self.cookNotes.toPlainText()
            if notes != "":
                try:
                    file = codecs.open(notesNewFile,"w", encoding="utf-8")
                    file.write(notes)
                    file.close()
                except:
                    QMessageBox.critical(self, "Warning",  "Cannot write " + itemtext + ".txt")

        # Dish
        if not newdish:
            data[rowNbr-1] = newLine + "\n"
        try:
            file = codecs.open(Cooktimer_ItemFile,"w", encoding="utf-8")
        except:
            QMessageBox.critical(self, "Warning",  "Cannot write " + Cooktimer_ItemFile)
        if not newdish:
            newTip = "|".join(data[rowNbr-1].split("|")[1:]).replace("\n", "")+"\n"
            globals()['Item%s' % rowNbr].setStatusTip(newTip)
            globals()['Item%s' % rowNbr].setText(itemtext)
            globals()['Item%s' % rowNbr].setValueText(self.cooktime.valueText())
            if os.path.isfile(notesNewFile):
                globals()['Item%s' % rowNbr].setIcon(QIcon("/opt/cooktimer/icons/notes_white.png"))
                globals()['Item%s' % rowNbr].setIconSize(QSize(18,14))
            else:
                globals()['Item%s' % rowNbr].setIcon(QIcon(""))
            data = "".join(data)
        else:
            num_lines += 1
            newTip = "|".join(newLine.split("|")[1:])+"\n"
            globals()['Item%s' % num_lines].setStatusTip(newTip)
            globals()['Item%s' % num_lines].setText(itemtext)
            globals()['Item%s' % num_lines].setValueText(self.cooktime.valueText())
            globals()['clearButton%s' % num_lines].show()
            if os.path.isfile(notesNewFile):
                globals()['Item%s' % num_lines].setIcon(QIcon("/opt/cooktimer/icons/notes_white.png"))
                globals()['Item%s' % num_lines].setIconSize(QSize(18,14))
            globals()['Item%s' % num_lines].show()
            data = "".join(data) + newLine + "\n"
        file.write(data)
        file.close()

        msg = self.tr("Dish is successfully saved")
        os.system('run-standalone.sh dbus-send --type=method_call --dest=org.freedesktop.Notifications  \
            /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \
            string:"'+msg+'"')
        self.dialog.close()

if __name__ == '__main__':
    # QApplication controls things relating to a Qt application, like the main loop.
    # You should always instantiate it before using any QtGui related stuff.
    # See also:
    #   http://doc.trolltech.com/4.6/qapplication.html
    #import sys
    #from PySide.QtCore import QString
    app = QApplication(sys.argv)

    # Internationalization
    # QLocale does not work as it should when having separate device/language settings
    # locale = QLocale.system().name()
    locale = os.getenv('LANG')
    appTranslator = QTranslator()
    if appTranslator.load("/opt/cooktimer/translations/cooktimer_" + locale):
        app.installTranslator(appTranslator)
        QLocale.setDefault(locale)
        print 'Language file: ' + locale + ' loaded'
    else:
        print 'Language file: ' + locale + ' not found'
    #
    # Create an instance (calling __init__, too, of course) of our window subclassing QWidget
    w = MyMainWindow()
    # Show our window
    w.show()
    # Main event loop of Qt. This won't return until the program exits.
    app.exec_()
    sys.exit()
