def moveImagesToCommonFolder(source = sikuli.getParentFolder(), destination = ""):
    if destination == "":
        destination = _myImagesPath
    for foldername, subfolders, filenames in os.walk(source):
        for filename in filenames:
            file = os.path.join(foldername,filename)
            if source == sikuli.getBundleFolder():
                folderFilter = True
            else:
                folderFilter = foldername.endswith(".sikuli")
            if file.endswith(".png") and folderFilter:
                #print file
                myfilename = os.path.basename(file)
                myhash = getHash(file)
                newFile = os.path.join(destination, myfilename)
                newHash = getHash(file)
                if not os.path.exists(newFile):
                    shutil.move(file, destination)
                else:
                    print "----------", myfilename," is in ", destination
                    if newHash == myhash:
                        #print "duplicate found, removing it"
                        os.remove(file)
                    else:
                        print "cannot move :", file
 def user(message):
     if SikuliSettings.UserLogs:
         if Debug.printoutuser == None:
             if SikuliSettings.isMacApp:
                 Debug.printoutuser = "******"
             else:
                 Debug.printoutuser = sikuli.getBundleFolder()+ "UserLog.txt"
         with open(Debug.printoutuser, "a") as f:
             if SikuliSettings.UserLogTime:
                 text = '[{} ({})] {}'.format(SikuliSettings.UserLogPrefix,'{:%m/%d/%y %I:%M:%S %p}'.format(datetime.datetime.now()).lstrip("0").replace(" 0", " "), message)
             else:
                 text = '[{}] {}'.format(SikuliSettings.UserLogPrefix, message)
             f.write(text+"\n")
    def setUserLogFile(fileName, premake=True):
        if fileName == None:
            fileName = ""
            return False
        else:
            if "" == fileName:
                if SikuliSettings.isMacApp:
                    Debug.printoutuser = "******"
                else:
                    Debug.printoutuser = sikuli.getBundleFolder()+ "UserLog.txt"
            else:
                Debug.printoutuser = fileName

            if premake:
                try:
                    with open(Debug.printoutuser, "a") as f:
                        f.write("")
                    return True
                except:
                    Debug.printoutuser = None
                    print "[Error] User logfile %s not accessible - check given path"% fileName
                    return False
def _init():
    SikuliSettings.ActionLogs = False
    SikuliSettings.InfoLogs = False
    #SikuliSettings.DebugLogs = False

    #print "initializing"
    global myOS
    global _sitePackages
    global _logToFolder
    global _imageUpdating
    global _errorFile
    global _artifactFolder
    global _partialHTML
    global _myImagesPath
    global _showHeader
    global _textLog
    global _myEvent
    _myEvent = threading.Event()
    _myEvent.set()

    #OS-specific variables section
    my_OS = sikuli.Env.getOS()
    splitOSVersion = sikuli.Env.getOSVersion().split('.')
    my_OSVersion = splitOSVersion[0]+"."+splitOSVersion[1]
    if my_OS == sikuli.OS.LINUX:
        myOS = "L"
        _sikuliRepo = os.path.join(os.path.expanduser('~'),".Sikulix/")
        _vagrantFolder = "/vagrant/"
        _homeFolder = os.path.expanduser('~')+"/"
        os_options = {
        "3.2": "UbuntuPrecise",
        "3.13": "UbuntuTrusty",
        "4.4" : "UbuntuXenial",
        "3.8" : "Wasta12",
        "3.16": "Wasta14"
        }
    elif my_OS == sikuli.OS.WINDOWS:
        myOS = "W"
        _sikuliRepo = os.path.join(os.getenv('APPDATA'),"Sikulix\\")
        _vagrantFolder = "C:/vagrant/"
        _homeFolder = os.getenv('USERPROFILE')+"\\"
        os_options = {
        "6.0": "WindowsVista",
        "6.1":"Windows7",
        "6.2":"Windows8",
        "6.3":"Windows8.1",
        "10.0": "Windows10",
        }
    elif my_OS == OS.MAC:
        myOS = "M"
        _sikuliRepo = os.path.join(os.path.expanduser('~'),"Library/Application Support/Sikulix/")
        _homeFolder = os.path.expanduser('~')+"/"
    else:
        myOS = "N"
        print "Unsupported OS."
        exit(1)
    _sitePackages = os.path.join(_sikuliRepo, "Lib/site-packages")

    # Determine Logging Folder
    # A non-existent, empty, invalid logFolder.txt or one with "image_updater" keeps all logs in the .sikuli folder of each test.
    # A logFolder.txt with a valid path keeps all logs in one log in that folder.
    # A logFolder.txt with "vagrant" keeps all logs in the default vagrant folder.
    # Helper scripts logs are kept in the top level folder.
    try:
        with open(os.path.join(_sitePackages, "logFolder.txt"), "r") as f:
            rawLogFolder = os.path.normpath((f.readline()).strip())
    except IOError:
        rawLogFolder = "."

    if "image_updater" in rawLogFolder:
        _logToFolder = sikuli.getBundleFolder()
        updateImages()
        #setFindFailedResponse(PROMPT) #Native support for capturing in 1.1.1
    elif "vagrant" in rawLogFolder:
        _logToFolder = _vagrantFolder
    else:
        if rawLogFolder != "." and os.path.exists(rawLogFolder):
            _logToFolder = rawLogFolder
        else:
            if len(rawLogFolder)>1:
                print "ERROR: LogFolder.txt contents not usable. Using default behavior."
            _logToFolder = sikuli.getBundleFolder()
    Debug.setUserLogFile(os.path.join(_logToFolder, "UserLog.txt"), premake=False)

    try:
        myImagesFolder = os_options[my_OSVersion]
    except:
        sikuli.popup("The version of "+str(my_OS)+" is not supported yet.")

    #Determing where the common immage folders are and make them (default) if they are missing.
    parentPath = sikuli.getParentPath()
    parentFolder = os.path.basename(parentPath)
    if os.path.basename(parentPath) == "helpers":
        _myImagesPath = os.path.join(os.path.dirname(parentPath), "images", myImagesFolder)
    else:
        _myImagesPath = os.path.join(parentPath, "images", myImagesFolder)
    if not os.path.exists(_myImagesPath):
        error_message = "WARNING: The following Common Image Path is missing: "+_myImagesPath
        print error_message
        #sikuli.popup(error_message)
        if sikuli.Sikulix.prefLoad("cib") == "ASK":
            buttons = ["Make", "Cancel","Exit Program"]
            choice = JOptionPane().showOptionDialog(None, error_message , "Common Image Path Does Not Exist.",  JOptionPane.PLAIN_MESSAGE, 0, None, buttons, buttons[0])
        elif sikuli.Sikulix.prefLoad("cib") == "MAKE":
            choice = 0
        elif sikuli.Sikulix.prefLoad("cib") == "SKIP":
            choice = 1
        else:
            print "Common Image Behavior not correct."

        if choice == -1:
            pass #Window Closed
        elif choice == 0:
            #creat path
            try:
                os.makedirs(_myImagesPath)
                sikuli.addImagePath(_myImagesPath)
            except:
                sikuli.popup(_myImagesPath+" could not be created.")
        elif choice == 1:
            pass
        elif choice == 2:
            exit(1)
        else:
            #print "You added an extra button and it doesn't do anything."
            pass
    else:
        sikuli.addImagePath(_myImagesPath)

    #myProjectsPath = os.path.join(parentPath, "projects")

    # If a file with the given filename already exists, the Logger will
    # just keep writing to the end of that file.
    # *_errorFile* is the path to the text log.
    # *_logToFolder* is the path to the directory which stores the
    # html log and its assiocated images.
    _artifactFolder = os.path.join(_logToFolder, "log")
    _errorFile = os.path.join(_artifactFolder,"error_log")
    #with open(_errorFile, "a") as f:
    #    f.write("")

    # Create the log folder if it doesn't exist
    if not os.path.exists(_artifactFolder):
        os.makedirs(_artifactFolder)
        _partialHTML = os.path.join(_artifactFolder, "mylog.log")
    # Otherwise, see if there's already a log file
    else:
        glob_result = glob.glob(_artifactFolder + "/*.log")
        if len(glob_result) == 1:
            _partialHTML = glob_result[0]
        else:
            _partialHTML = os.path.join(_artifactFolder, "mylog.log")

    # Add the CSS stylesheet to the log folder, if it's not there already.
    if not os.path.exists(os.path.join(_artifactFolder, "log.css")):
        shutil.copyfile(os.path.join(_sitePackages,"log.css"),
                        os.path.join(_artifactFolder, "log.css"))
    if _showHeader:
        #if imported this header shows the filepath of the main script
        #if runScript this header shows the filepath of the helper script
        doc, tag, text = Doc().tagtext()
        with tag("tr"):
            with tag("td", style="text-align: center; background-color:lightskyblue", colspan="7"):
                text(time.strftime("%x %H:%M:%S")+": "+sikuli.getBundleFolder())
        with open(_partialHTML, "a") as f:
            f.write(doc.getvalue())
        _registerHTMLgenerator()