def disconnectNode(self, isQuit):
        """ close the connection with the node """

        debug.debug_info("navigator.disconnectNode(" + str(isQuit) + ")")
        if (self.isConnected == 1):
            #print "navigator.disconnectNode()"
            #f = file("Debug.txt", 'a')
            #f.write("navigator.disconnectNode()\n")
            #f.close()
            try:
                # save the last position of the node
                self.saveLastPositionNode(isQuit)

                # close the services
                self.closeChatService()
                self.closeDisplay2dService()

                # close the connection with the node
                self.my_node.closeConnection()
                self.isConnected = 0

                # clear ihm
                self.ihm.clear2dView()
                self.ihm.clearChatterList()               
                
                return 1

            except:
                #sys.stderr.write("EXCEPTION : Problem in the node deconnection\n")
                commun.displayError(self.ihm, "Problem in the disconnection from the node !")
                return 0
    def OnRenameButton(self, event):
        """ rename the image file selected """

        # check if an item is selected
        if (self.imageIndice != -1):
            dlg = wxTextEntryDialog(self, 'Rename your avatar :', 'Rename avatar', self.imageList[self.imageIndice], wxOK|wxCANCEL)
            dlg.Center(wxBOTH)
            if dlg.ShowModal() == wxID_OK:

                # get the new image name
                image_name = dlg.GetValue()
                if image_name == "":
                    commun.displayError(self, "Can't rename the avatar file : your name is empty !")
                else:
                    src = self.avatarsDir + os.sep + self.imageList[self.imageIndice] + ".png"
                    dest = self.avatarsDir + os.sep + image_name  + ".png"
                    # control the doublon
                    if os.path.isfile(dest):
                        commun.displayError(self, "This avatar name already exists. Please, choose another name.")
                    else:
                        # rename the image file
                        os.rename(src, dest)
                        # modify the image item in the list
                        self.imageList[self.imageIndice] = image_name
                        self.imagesListBox.SetString(self.imageIndice, image_name)

                # destroy the dialog box
                dlg.Destroy()
    def connectNode(self, node_host, node_port):
        """ establish the connection with the node passed in parameter """

        debug.debug_info("navigator.connectNode()")
 
        try:
            # launch the node connection
            self.my_node = MyNode(node_host, node_port, self)
            self.my_node.launchConnection()

            # get information on the connected node
            self.my_node.getInfos()

            # add the services
            self.addChatService()
            self.addDisplay2dService()

            # change the connected status
            self.isConnected = 1

            # draw the 2d View after connection
            self.draw2dView()

            # refresh chatter
            #self.displayChatterList()
            return 1

        except:        
            commun.displayError(self.ihm, "Problem in the connection with the node !")
            return 0
    def saveNodeFile(self):
        """ save the nodes file with the value store in the nodes list """

        # open file 'nodes.txt'
        try:
            f = file(self.nodesFile, 'w')
        except:
            commun.displayError(self, 'Can not open the file %s' %self.nodesFile)
            return 0

        # write node infos in the nodes file
        for node in self.nodeList:
            pseudo = node['pseudo']
            host = node['host']
            port = str(node['port'])
            posX = str(node['posX'])
            posY = str(node['posY'])
            isDistant = str(node['isDistant'])
            isConnected = str(node['isConnected'])
            line = pseudo + ';' + host + ';'+ port + ';' + posX + ';' + posY + ';' + isDistant + ';' + isConnected + '\n'
            f.write(line)

        f.close()

        return 1
    def imageGeneration(self):
        """ Generate the result image """
        debug.debug_info("createAvatarDialog.imageGeneration()")

        # control errors
        if not self.imageFileName:
            commun.displayError(self, 'Please, select your image file !')
            return
        else:
            # open image files
            maskImg = PIL.Image.open(self.maskFileName)
            fileImg = PIL.Image.open(self.imageFileName)

            # contol the file size (for resizing)
            (width, height) = fileImg.size
            if ((width < self.avatarSize) or (height < self.avatarSize)):
                commun.displayError(self, 'Your image has a bad format. Please, choose a bigger one !')
                return

            # resize the image file with the size of avatars
            maskImg = maskImg.convert("RGBA")
            fileImg = fileImg.resize((self.avatarSize, self.avatarSize))
            fileImg = fileImg.convert("RGBA")
            resultImg = PIL.ImageChops.multiply(fileImg, maskImg)
            return resultImg
    def OnNewLocalNodeButton(self, event):
        """ create a new local node in the list """

        dlg = newLocalNodeDialog(self)
        if dlg.ShowModal() == wxID_OK:
            pseudo = dlg.pseudoTextCtrl.GetValue()
            if pseudo == "":
                commun.displayError(self, "Can't create the node : your node pseudo is empty !")
            else:
                #host = socket.gethostbyname(socket.gethostname())
                while 1:
                    # find a port available for the node
                    port = random.randint(1024, 2**16L)
                    try:
                        # start the new node
                        self.startNode(pseudo, port)
                        break
                    except:
                        # may be the port is already used
                        time.sleep(0.2)
                # host
                # DEB MOD MCL
                #addrinfo=socket.getaddrinfo(socket.gethostname(), port)
                #address=addrinfo[len(addrinfo)-1][4]
                #host=address[0]
                filename = str(pseudo)+".host"
                while filename not in os.listdir("."):
                    time.sleep(0.1)

                f = file(filename, 'r')
                host = f.readlines()[0]
                f.close()
                # FIN MOD MCL

                list={'pseudo':pseudo, 'host':host, 'port':port, 'posX':'', 'posY':'', 'isDistant':0, 'isConnected':0}

                # store the new node in the lists
                self.nodeList.append(list)
                self.pseudoList.append(pseudo)
                self.nodesListBox.Append(pseudo)

                # save the new node in the nodes file
                self.saveNodeFile()

        dlg.Destroy()
def writeConfParameterValue(parameter, value):
    """ write the value of a parameter in the conf file """

    # variables initialization
    global confFile
    list = []
    indice = 0

    # open the conf file in read mode
    try:
        f = file(confFile, 'r')

        # read and close file
        list = f.readlines()
        f.close()

    except:
        pass

    for line in list:
        param, val = line[:len(line) -1].split('=')
        if param == parameter:
            # change the line in the list
            line = string.join((parameter, str(value)), '=')
            line += '\n'
            list[indice] = line
            break
        indice +=1

    # creation mode
    if indice >= len(list):
        # write the new line in the list
        line = string.join((parameter, str(value)), '=')
        line += '\n'
        list.append(line)

    # save the new lines in file
    try:
        f = file(confFile, 'w')
        f.writelines(list)
        # close file
        f.close()
    except:
        message="Can't open the file " + confFile
        commun.displayError(self, message)
    def OnOkButton(self, event):
        """ teleportation of the connected node to the position filled """

        # check if the navigator is connected to a node
        if (self.navigator.getIsConnected() == 1):
            posx = self.xposTextCtrl.GetValue()
            posy = self.yposTextCtrl.GetValue()

            # errors control
            if posx == "":
                commun.displayError(self, "Your flag X coordinate is empty !")
            elif posy == "":
                commun.displayError(self, "Your flag Y coordinate is empty !")
            else:
                try:
                    x = long(posx)
                except:
                    commun.displayError(self, "Your flag X coordinate has a bad format. Please, enter an integer.")
                    return 0
                try:
                    y = long(posy)
                except:
                    commun.displayError(self, "Your flag Y coordinate has a bad format. Please, enter an integer.")
                    return 0

                # get the node AR to generate noise near the selected point
                ar = self.navigator.getNodeAr()
                #debug.debug_info("getNodeAr() -> " + str(ar))
                deltaNoise = long(random.random()*ar/10)
                #debug.debug_info("deltaNoise = [%d]" %deltaNoise)
                x = long(x + deltaNoise)
                y = long(y + deltaNoise)

                # Inform the navigator of the new position
                self.navigator.jumpMyNode(str(x), str(y))

                # close the dialog box
                self.Close(FALSE)
        else:
            commun.displayError(self, 'Sorry you are not connected !')
    def OnNewDistantNodeButton(self, event):
        """ create a new distant node in the list """

        dlg = newDistantNodeDialog(self)
        if dlg.ShowModal() == wxID_OK:
            host = dlg.hostTextCtrl.GetValue()
            port = dlg.portTextCtrl.GetValue()
            if host == "":
                commun.displayError(self, "Can't create the node : your node host is empty !")
            elif port == "":
                commun.displayError(self, "Can't create the node : your node port is empty !")
            else:
                pseudo = host + ":" + port
                list={'pseudo':pseudo, 'host':host, 'port':port, 'posX':'', 'posY':'', 'isDistant':1, 'isConnected':0}

                # store the new node in the lists
                self.nodeList.append(list)
                self.pseudoList.append(pseudo)
                self.nodesListBox.Append(pseudo)

                # save the new node in the nodes file
                self.saveNodeFile()
        dlg.Destroy()
    def OnOkButton(self, event):
        """ Save the avatar created by the user """

        # get the avatar name
        avatarName = self.nameTextCtrl.GetValue()
        if avatarName == "":
            commun.displayError(self, "Your avatar name is empty !")
        else:
            # generate the result image
            resultImage=self.imageGeneration()

            if resultImage:
                # save the result file with the name filled by the user
                avatarFile = self.avatarDir + os.sep + avatarName + ".png"
                # control the doublon
                if os.path.isfile(avatarFile):
                    commun.displayError(self, "This avatar name already exists. Please, choose another name.")
                    return 0

                resultImage.save(avatarFile)

                # close the dialog box
                self.Close(FALSE)
    def initPositionValues(self):
        """ init the position values with the position of the connected node """
        debug.debug_info("newFlagDialog.initPositionValues()")
        debug.debug_info("FlagFile : " + self.flag_name)

        # flag modification
        if self.flag_name:
            # open the flag file
            flagFile = commun.FLAG_DIR_NAME + os.sep + self.flag_name
            try:
                f = file(flagFile, 'r')
            except:
                commun.displayError(self, "Can not open the file " + flagFile)
                return 0

            # read file and close
            line = f.read()
            f.close()
            try:
                name, posX, posY = line.split(';')
            except:
                commun.displayError(self, 'The file %s has a bad format !' %self.flag_name)
                # close the dialog box
                self.Close(FALSE)
                return 0

            # set default parameters
            self.nameTextCtrl.SetValue(name)
            self.xposTextCtrl.SetValue(posX)
            self.yposTextCtrl.SetValue(posY)

         # new flag -> check if the navigator is connected to a node
        elif (self.navigator.getIsConnected() == 1):
            posX = self.navigator.getNodePosX()
            posY = self.navigator.getNodePosY()
            self.xposTextCtrl.SetValue(str(posX))
            self.yposTextCtrl.SetValue(str(posY))
    def OnFlagsGoto(self, event):
        """ Go to the flag selected in the menu """
        id = event.GetId()
        flag = self.menuFlags.GetLabel(id)
        debug.debug_info("ihm.OnFlagsGoto(" + flag +")")

        # display a confirmation message
        message = 'Are you sure you want to go to this flag : ' + flag + ' ?'
        dlg = wxMessageDialog(self, message, 'Go to flag', wxOK|wxCANCEL|wxCENTRE|wxICON_QUESTION)
        dlg.Center(wxBOTH)
        if dlg.ShowModal() == wxID_OK:
            # open the flag file
            flagFile = "Flags" + os.sep + flag
            try:
                f = file(flagFile, 'r')
            except:
                commun.displayError(self, 'Can not open the file %s' %flagFile)
                return 0

            # read file and close
            line = f.read()
            f.close()
            try:
                name, posX, posY = line.split(';')
            except:
                commun.displayError(self, 'The file %s has a bad format !' %flagFile)
                return 0
            
            # get the node AR to generate noise near the selected point
            ar = self.navigator.getNodeAr()
            debug.debug_info("getNodeAr() -> " + str(ar))
            deltaNoise = long(random.random()*ar/10)            
            posX = long(posX) + deltaNoise
            posY = long(posY) + deltaNoise
                
            # jump to the flag position
            self.navigator.jumpMyNode(str(posX), str(posY))
    def OnOkButton(self, event):
        """ save the flag with the name filled by the user """

        # get the flag parameters
        name = self.nameTextCtrl.GetValue()
        posX = self.navigator.getNodePosX()
        posY = self.navigator.getNodePosY()

        # errors control
        if name == "":
            commun.displayError(self, "Your flag name is empty !")
        elif posX == "":
            commun.displayError(self, "Your flag X coordinate is empty !")
        elif posY == "":
            commun.displayError(self, "Your flag Y coordinate is empty !")
        else:
            flagFile = commun.FLAG_DIR_NAME + os.sep + name

            # control the doublon
            if os.path.isfile(flagFile):
                commun.displayError(self, "This flag name already exists. Please, choose another name.")
                return 0

            # open the flag file
            try:
                f = file(flagFile, 'w')
            except:
                commun.displayError(self, 'Can not open the file %s' %flagFile)
                return 0

            # save the parameters in the flag file
            line = name + ';' + str(posX) + ';'+ str(posY)
            f.write(line)
            f.close()

            # close the dialog box
            self.Close(FALSE)
    def OnChooseButton(self, event):
        """ send the avatar selected to the neighbors """

        # check if an item is selected
        if (self.imageIndice != -1):
            # check if the navigator is connected to a node
            if (self.navigator.getIsConnected() == 1):
                # display a confirmation message
                message = 'Are you sure you want to send this avatar to your neighbors : ' + self.imageList[self.imageIndice] + ' ?'
                dlg = wxMessageDialog(self, message, 'Choose avatar', wxOK|wxCANCEL|wxCENTRE|wxICON_QUESTION)
                dlg.Center(wxBOTH)
                if dlg.ShowModal() == wxID_OK:
                    image_name = self.avatarsDir + os.sep + self.imageList[self.imageIndice] + ".png"
                    # copy the avatar in the avatarDir
                    avatarFile = commun.AVATAR_DIR_NAME + os.sep + self.navigator.getNodePseudo() + "_" + self.imageList[self.imageIndice] + ".png"
                    shutil.copyfile(image_name, avatarFile)
                    # resize the avatar file
                    resizeFile = commun.chgSize(avatarFile)
                    # send the file to the navigator                    
                    self.navigator.sendImage(avatarFile, resizeFile)
                    # close the dialog box
                    self.Close(FALSE)
            else:
                commun.displayError(self, 'Sorry you are not connected !')
    def OnOkButton(self, event):
        """ save the flag with the parameter filled by the user """

        # get the parameters filled by the user
        name = self.nameTextCtrl.GetValue()
        posX = self.xposTextCtrl.GetValue()
        posY = self.yposTextCtrl.GetValue()

        # errors control
        if name == "":
            commun.displayError(self, "Your flag name is empty !")
        elif posX == "":
            commun.displayError(self, "Your flag X coordinate is empty !")
            messageDialog.ShowModal()
        elif posY == "":
            commun.displayError(self, "Your flag Y coordinate is empty !")
        else:
            try:
                x = long(posX)
            except:
                commun.displayError(self, "Your flag X coordinate has a bad format. Please, enter an integer.")
                return 0
            try:
                y = long(posY)
            except:
                commun.displayError(self, "Your flag Y coordinate has a bad format. Please, enter an integer.")
                return 0

            flagFile = commun.FLAG_DIR_NAME + os.sep + name

            # control the doublon
            if os.path.isfile(flagFile):
                commun.displayError(self, "This flag name already exists. Please, choose another name.")
                return 0

            # flag modification
            if self.flag_name:
                # rename the flag file
                flagFile_old = commun.FLAG_DIR_NAME + os.sep + self.flag_name
                os.rename(flagFile_old, flagFile)

            # open the flag file
            try:
                f = file(flagFile, 'w')
            except:
                commun.displayError(self, 'Can not open the file %s' %flagFile)
                return 0

            # save the parameters in the flag file
            line = name + ';' + posX + ';'+ posY
            f.write(line)
            f.close()

            # close the dialog box
            self.Close(FALSE)