Example #1
0
def doClean(rule, dirObj, toProcess, srcDir, dstDir):
    """
    Function to execute the core of the clean operation. It is in its own
    function because it is used also by the export rule.
    """

    # Identical source and destination, useless operation
    if os.path.abspath(srcDir) == os.path.abspath(dstDir):
        return

    for datafile in toProcess:

        adagio.logDebug(rule, dirObj, ' EXEC ' + datafile)

        # If file not found, terminate
        if not os.path.exists(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Remove the srcDir prefix
        dstFile = datafile.replace(srcDir, '', 1)
        # If the result has a slash, remove it
        if dstFile[0] == '/':
            dstFile = dstFile[1:]
        # Derive the destination file name
        dstFile = os.path.abspath(os.path.join(dstDir, dstFile))

        # If file is not there, bypass
        if not os.path.exists(dstFile):
            continue

        # Proceed with the cleaning (dump the file name being deleted)
        rules.remove(dstFile)
def __validate_environment():
   '''
   Checks to see if the current environment is valid to run this script in.
   If it is not, an error message is displayed to explain the problem.
   
   Returns True if the current environment is valid, False if it is not.
   '''
   
   # the minimum versions required for a valid environment
   REQUIRED_MAJOR=0
   REQUIRED_MINOR=9
   REQUIRED_BUILD=165
   
   valid_environment = True
   try:
      version = re.split(r'\.', ComicRack.App.ProductVersion) 
      def hash( major, minor, build ):
         return float(sstr(major * 5000 + minor) + "." + sstr(build)) 
      
      valid_environment = \
         hash(int(version[0]),int(version[1]), int(version[2])) >= \
            hash(REQUIRED_MAJOR, REQUIRED_MINOR, REQUIRED_BUILD)
         
      if not valid_environment:
         log.debug("WARNING: script requires ComicRack ", REQUIRED_MAJOR, '.',
            REQUIRED_MINOR, '.', REQUIRED_BUILD, ' or higher.  Exiting...')
         MessageBox.Show( ComicRack.MainWindow, i18n.get("ComicRackOODText"),
            i18n.get("ComicRackOODTitle"), MessageBoxButtons.OK, 
            MessageBoxIcon.Warning)
         
   except:
      log.debug_exc("WARNING: couldn't validate comicrack version")
      valid_environment = True
      
   return valid_environment
Example #3
0
def getProperty(config, rule, option):
    """
    Function that given a rule name of the form 'a.b.c.d' and an option name,
    gets the value obtained from the given config. The procedure works
    hierarchically. It first checks for the option value in the given rule,
    and if not found, it keeps asking for the values in the rules obtained by
    dropping the last suffix (from the last dot until the end of the rule
    name.
    """

    global _adagio_given_definiton_rule_name

    # If the rule is a.b.c, loop asking if we have the option a.b.c.option,
    # then a.b.option, and then a.option.
    partialRule = rule
    while partialRule != '':
        if config.has_option(_adagio_given_definiton_rule_name,
                             partialRule + '.' + option):
            result = config.get(partialRule, option)
            return result
        partialRule = partialRule.rpartition('.')[0]

    # If no hit so far, need to make one more test to see if the value is in the
    # DEFAULT rule
    try:
        result = config.get(rule, option)
        # Yes, the value is stored as in  DEFAULT
        return result
    except ConfigParser.InterpolationMissingOptionError, e:
        print i18n.get('incorrect_variable_reference').format(option)
        sys.exit(1)
Example #4
0
    def dumpOptions(self, rule, prefix):
        """
        Print the value of the options affecting the computations
        """


        # Remove the .vars from the end of the rule to fish for options
        rule = re.sub('\.?vars$', '', rule)
        if rule == '':
            rule = prefix
        basicPrefix = rule.split('.')[0]

        # Concatenate all the variable values and pass through pager (skip help
        # because it is supposed to be printed outside this function)
        str = i18n.get('var_preamble').format(prefix) + '\n\n'
        for (on, ov) in sorted(self.options.items(rule)):
            if on == 'help':
                continue
            
            # Get the help_message from the global dict (try first with the rule
            # name, and if not found, without it to find generic variables)
            help_message = adagio.variable_help_messages.get(basicPrefix + 
                                                             '.' + on)
            if help_message == None:
                help_message = adagio.variable_help_messages.get(on)

            # Create the string: value + help message
            str += ' - ' + on + ' = ' + ov + '\n'
            if help_message != None:
                str += '   ' + help_message + '\n\n'
            else:
                str += '   ' + i18n.get('user_defined_variable') + '\n\n'

        return str
Example #5
0
def test_configure_translation_forced(translator):
    rdftools.configure_translation(force_locale='tv')
    # Ensure we override the default system locale
    import i18n
    assert len(i18n.load_path) == 1
    assert i18n.get('locale') == 'tv'
    assert i18n.get('fallback') == 'en'
Example #6
0
def Execute(rule, dirObj, pad = None):
    """
    Execute the rule in the given directory
    """

    if pad == 'None':
        pad = ''

    (toProcess, remoteRules,
     optionsToSet, newExportDir) = prepareRule(rule, dirObj)

    # Loop over each directory
    for dirName in toProcess:
        adagio.logInfo(rule, dirObj, 'RECUR: ' + dirName)
        if not os.path.isdir(dirName):
            print i18n.get('not_a_directory').format(dirName)
            sys.exit(1)
        remoteDir = directory.getDirectoryObject(dirName, optionsToSet)

	if remoteDir.rule_list == []:
	    # If rule_list is empty, there is no Properties.dgo in that dir, skip execution
            continue

        # Execute the targets in the remote directory
        remoteDir.Execute(remoteRules, pad + '  ')

    return
Example #7
0
def clean(rule, dirObj):
    """
    Clean the files produced by this rule
    """
    
    adagio.logInfo(rule, dirObj, 'Cleaning')

    # Get the files to process
    toProcess = glob.glob(os.path.join(dirObj.current_dir, '*.xcf'))
    if toProcess == []:
        adagio.logDebug(rule, dirObj, i18n.get('no_file_to_process'))
        return

    # Loop over the source files to see if an execution is needed
    dstFiles = []
    dstDir = dirObj.getProperty(rule, 'src_dir')
    for datafile in toProcess:

        # If file not found, terminate
        if not os.path.isfile(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Derive the destination file name
        dstFile = os.path.splitext(os.path.basename(datafile))[0] + '.png'
        dstFile = os.path.abspath(os.path.join(dstDir, dstFile))

        if not os.path.exists(dstFile):
            continue

        rules.remove(dstFile)

    return
Example #8
0
   def checkCreateErroneousRule(self, ruleName, ruleDescription, ruleCode, ruleLog):
      print '  Check notifications'
      notification.waitText(self.browser, notification.Type.Success, i18n.get()["modals"]["dashboard"]["sub-windows"]["automation-center"]["ruleSuccessfullyCreated"])
      notification.waitSubText(self.browser, notification.Type.Error, i18n.get()["eventLogger"]["RuleFailed"].replace("__who__", ruleName))
      
      print '  Check rule was inserted in rules table'
      rulesTable = dashboard.automation.waitRulesTableHasNRules(self.browser, 1)

      ruleNumber = 0
      
      print '  Check rule data in rules table'
      self.assertEqual(len(dashboard.automation.getRuleDatas(rulesTable, ruleNumber)), 5)
      self.assertEqual(dashboard.automation.getRuleName(rulesTable, ruleNumber), ruleName)
      self.assertEqual(dashboard.automation.getRuleDescription(rulesTable, ruleNumber), ruleDescription)
      self.assertTrue(dashboard.automation.getRuleAutoStart(rulesTable, ruleNumber))

      buttons = dashboard.automation.getRuleButtons(rulesTable, ruleNumber)
      self.assertEqual(len(buttons), 4)
      self.assertTrue(tools.waitUntil(lambda: dashboard.automation.getRuleStartStopButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-enableDisable btn-success"))
      self.assertEqual(dashboard.automation.getRuleEditButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-edit btn-primary")
      self.assertEqual(dashboard.automation.getRuleRemoveButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-delete btn-danger")
      
      self.assertTrue(tools.waitUntil(lambda: dashboard.automation.getRuleState(rulesTable, ruleNumber) == dashboard.automation.RuleState.Error))
      
      print '  Check rule was created on disk (corresponding script file)'
      self.assertTrue(scripts.checkLocalRuleCodeById(1, ruleCode))
      self.assertTrue(tools.waitUntil(lambda: scripts.checkLocalRuleLogById(1, ruleLog)))
Example #9
0
def findOrAddTransform(styleFile, styleList, paths = None):
    """
    Simple dictionary storing XSL Transforms. The key is the given styleFile (which
    could be a string)
    """
    global _createdTransforms
    global _xml_parser
    
    theKey = ' '.join(styleList)

    # Get the last modification time of the given file to detect changes. First
    # filter files because there could be some URLs
    fileStyleList = [x for x in styleList if os.path.exists(x)]
    ftime = sys.float_info.max
    if fileStyleList != []:
        ftime = max([os.path.getmtime(x) for x in fileStyleList])

    (transform, tstamp) = _createdTransforms.get(theKey, (None, None))
    if (transform != None) and (ftime <= tstamp):
        # HIT
        adagio.logDebug('treecache', None, 'HIT: ' + str(styleFile))
        return transform

    # expand includes and create transformation object
    try:
        transform = etree.parse(styleFile, _xml_parser)
    except etree.XMLSyntaxError, e:
        print i18n.get('severe_parse_error').format(styleFile)
        print str(e)
        sys.exit(1)
Example #10
0
def clean(rule, dirObj):
    """
    Clean the files produced by this rule
    """

    adagio.logInfo(rule, dirObj, 'Cleaning')

    # Get the files to process
    toProcess = rules.getFilesToProcess(rule, dirObj)
    if toProcess == []:
        return

    # Loop over all source files to process
    dstDir = dirObj.getProperty(rule, 'dst_dir')
    nupOption = dirObj.getProperty(rule, 'nup')
    for datafile in toProcess:

        # If file not found, terminate
        if not os.path.isfile(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Derive the destination file name
        dstFile = os.path.splitext(os.path.basename(datafile))[0] + \
            '-' + nupOption + os.path.splitext(os.path.basename(datafile))[1]
        dstFile = os.path.abspath(os.path.join(dstDir, dstFile))

        if not os.path.exists(dstFile):
            continue

        rules.remove(dstFile)

    return
Example #11
0
def getFilesToProcess(rule, dirObj):
    """
    Get the files to process by expanding the expressions in "files" and
    concatenating the src_dir as prefix.
    """

    # Safety guard, if srcFiles is empty, no need to proceed. Silence.
    srcFiles = dirObj.getProperty(rule, 'files').split()
    if srcFiles == []:
        adagio.logDebug(rule, dirObj, i18n.get('no_file_to_process'))
        return []

    srcDir = dirObj.getProperty(rule, 'src_dir')
    toProcess = []
    for srcFile in srcFiles:
        found = glob.glob(os.path.join(srcDir, srcFile))

        # Something was given in the variable, but nothing was found. Warn the
        # user but proceed.
        if found == []:
            print i18n.get('file_not_found').format(srcFile)
            # Exiting here sometimes is needed (i.e. when searching for a source
            # file to process) and sometimes it's ok (i.e. when searching for
            # files to export). There should be a boolean to select either
            # behavior
            # sys.exit(1)

        toProcess.extend(found)

    return toProcess
    def __build_advancedtab(self):
        ''' builds and returns the "Advanced" Tab for the TabControl '''

        tabpage = TabPage()
        tabpage.Text = i18n.get("ConfigFormAdvancedTab")

        # 1. --- a description label for this tabpage
        label = Label()
        label.UseMnemonic = False
        label.AutoSize = True
        label.Location = Point(14, 25)
        label.Size = Size(299, 17)
        label.Text = i18n.get("ConfigFormAdvancedText")

        # 2. --- build the update checklist (contains all the 'data' checkboxes)
        tbox = RichTextBox()
        tbox.Multiline = True
        tbox.MaxLength = 65536
        tbox.WordWrap = True
        tbox.Location = Point(15, 50)
        tbox.Size = Size(355, 200)

        menu = ContextMenu()
        items = menu.MenuItems
        items.Add(MenuItem(i18n.get("TextCut"), lambda s, ea: tbox.Cut()))
        items.Add(MenuItem(i18n.get("TextCopy"), lambda s, ea: tbox.Copy()))
        items.Add(MenuItem(i18n.get("TextPaste"), lambda s, ea: tbox.Paste()))
        tbox.ContextMenu = menu
        self.__advanced_tbox = tbox

        # 3. --- add 'em all to the tabpage
        tabpage.Controls.Add(label)
        tabpage.Controls.Add(self.__advanced_tbox)

        return tabpage
Example #13
0
   def checkCreateErroneousRule(self, ruleName, ruleDescription, ruleCode, ruleLog):
      print ('  Check notifications')
      notification.waitText(self.browser, notification.Type.Success, i18n.get()["modals"]["dashboard"]["sub-windows"]["automation-center"]["ruleSuccessfullyCreated"])
      notification.waitSubText(self.browser, notification.Type.Error, i18n.get()["eventLogger"]["RuleFailed"].replace("{{who}}", ruleName))
      
      print ('  Check rule was inserted in rules table')
      rulesTable = dashboard.automation.waitRulesTableHasNRules(self.browser, 1)

      ruleNumber = 0
      
      print ('  Check rule data in rules table')
      self.assertEqual(len(dashboard.automation.getRuleDatas(rulesTable, ruleNumber)), 5)
      self.assertEqual(dashboard.automation.getRuleName(rulesTable, ruleNumber), ruleName)
      self.assertEqual(dashboard.automation.getRuleDescription(rulesTable, ruleNumber), ruleDescription)
      self.assertTrue(dashboard.automation.getRuleAutoStartState(rulesTable, ruleNumber))

      buttons = dashboard.automation.getRuleButtons(rulesTable, ruleNumber)
      self.assertEqual(len(buttons), 5)
      self.assertTrue(tools.waitUntil(lambda: dashboard.automation.getRuleStartStopButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-enableDisable btn-success"))
      self.assertEqual(dashboard.automation.getRuleStartStopButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-startStop btn-success")
      self.assertEqual(dashboard.automation.getRuleEditButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-edit btn-primary")
      self.assertEqual(dashboard.automation.getRuleDuplicateButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-duplicate btn-primary")
      self.assertEqual(dashboard.automation.getRuleRemoveButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-delete btn-danger")

      
      self.assertTrue(tools.waitUntil(lambda: dashboard.automation.getRuleState(rulesTable, ruleNumber) == dashboard.automation.RuleState.Error))
      
      print ('  Check rule was created on disk (corresponding script file)')
      self.assertTrue(scripts.checkLocalRuleCodeById(1, ruleCode))
      self.assertTrue(tools.waitUntil(lambda: scripts.checkLocalRuleLogById(1, ruleLog)))
Example #14
0
def obtainXincludes(files):
    """
    Obtain the files included using xinclude in the given file. Return a list
    with the absolute filenames
    """

    # Remember the old current directory because we are going to modify it
    old_cwd = os.getcwd()

    result = set([])
    for fileName in files:
        # We only accept absolute paths
        if not os.path.isabs(fileName):
            fileName = os.path.abspath(fileName)

        # Get the directory where the file is located and change cwd
        fDir = os.path.dirname(fileName)
	os.chdir(fDir)

        # Get the file parsed without expanding the xincludes
        root = treecache.findOrAddTree(fileName, False)

        # Path to locate the includes and dir of the given file
        includePath = '//{http://www.w3.org/2001/XInclude}include'

        # Obtain the included files
        includeFiles = \
            set([os.path.join(
                    x.attrib.get('{http://www.w3.org/XML/1998/namespace}base',
                                 ''),
                    x.attrib.get('href'))
                 for x in root.findall(includePath)
                 if x.attrib.get('href') != None and \
                     (x.attrib.get('parse') == None or
                      x.attrib.get('parse') == 'xml')])

        # Traverse all the include files
        for includeFile in includeFiles:
            # Locate the file applying Adagio search rules
            # locatedFile = dependency.locateFile(includeFile, [fDir])
            locatedFile = treecache.xml_resolver.resolve_file(includeFile)

            # If not found, notify and terminate
            if locatedFile == None:
                print i18n.get('file_not_found').format(includeFile)
                print i18n.get('included_from'), fileName
                sys.exit(1)

            if os.path.dirname(os.path.abspath(locatedFile)) == fDir:
                # If it is in the same dir, prepare to traverse
                files.append(locatedFile)
            else:
                # If in another dir, append to the result
                result.add(os.path.abspath(locatedFile))

    # restore the original cwd
    os.chdir(old_cwd)

    return result
Example #15
0
def Execute(rule, dirObj):
    """
    Execute the rule in the given directory
    """

    global has_executable

    if has_executable == '':
	has_executable = adagio.findExecutable(rule, dirObj)

    # If the executable is not present, notify and terminate
    if not has_executable:
        print i18n.get('no_executable').format(dirObj.options.get(rule, 'exec'))
        if dirObj.options.get(rule, 'partial') == '0':
            sys.exit(1)
        return

    # Get the files to process, if empty, terminate
    toProcess = rules.getFilesToProcess(rule, dirObj)
    if toProcess == []:
        adagio.logDebug(rule, dirObj, i18n.get('no_file_to_process'))
        return

    # Loop over all source files to process
    executable = dirObj.getProperty(rule, 'exec')
    extraArgs = dirObj.getProperty(rule, 'extra_arguments')
    # The command is soffice --nologo --invisible --headless
    #                        --convert-to pdf *.doc
    command = [executable, '--nologo', '--invisible', '--headless',
               '--convert-to', 'pdf']
    command.extend(extraArgs.split())
    dstDir = dirObj.getProperty(rule, 'src_dir')
    for datafile in toProcess:
        adagio.logDebug(rule, dirObj, ' EXEC ' + datafile)

        # If file not found, terminate
        if not os.path.isfile(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Derive the destination file name
        dstFileName = os.path.splitext(os.path.basename(datafile))[0] + \
            '.pdf'
        dstFile = os.path.abspath(os.path.join(dstDir, dstFileName))

        # Perform the execution
        command.append(datafile)
        # command.append('macro:///Tools.MSToPDF.ConvertMSToPDF(' + datafile + ')')

        rules.doExecution(rule, dirObj, command, datafile, dstFile,
                            stdout = adagio.userLog)
        command.pop(-1)

    # End of loop over all src files

    return
Example #16
0
def prepareRule(rule, dirObj):
    """
    Obtain the directories to process, calculate the options to set in the
    remote execution and obtain the remote rules.

    Return:

    (list of dirs to process, remote rules, options to set in the remote exec)
    """

    # Get the directories to process from the files option
    toProcess = []
    for srcDir in dirObj.getProperty(rule, 'files').split():
        newDirs = glob.glob(srcDir)
        if newDirs == []:
            print i18n.get('file_not_found').format(srcDir)
            sys.exit(1)
        toProcess.extend(glob.glob(srcDir))

    # Add the files included in files_included_from
    filesIncluded = \
        obtainXincludes(dirObj.getProperty(rule, 'files_included_from').split())

    # The list of dirs is extended with a set to avoid duplications
    toProcess.extend(set(map(lambda x: os.path.dirname(x), filesIncluded)))

    # If there are no files to process stop
    if toProcess == []:
        adagio.logDebug(rule, dirObj, i18n.get('no_file_to_process'))
        return (toProcess, [], None, '')

    # Translate all paths to absolute paths
    toProcess = map(lambda x: os.path.abspath(x), toProcess)

    # Rules to execute in the remote directory
    remoteRules = dirObj.getProperty(rule, 'rules').split()

    # Create the option dict for the remote directories
    optionsToSet = []
    newExportDir = dirObj.getProperty(rule, 'export_dst')
    if newExportDir != '':
        # If a new dst_dir has been specified, include the options to modify
        # that variable for each of the rules
        if remoteRules != []:
            # If there are some given rules, use them
            optionsToSet = [x + ' dst_dir ' + newExportDir
                            for x in remoteRules if x.startswith('export')]
        else:
            # If no rule is given, leave the option in the export.dst_dir
            # to its default value default
            optionsToSet = ['export dst_dir ' + newExportDir]

    adagio.logInfo(rule, dirObj, 'NEW Options = ' + ', '.join(optionsToSet))

    return (toProcess, remoteRules, optionsToSet, newExportDir)
Example #17
0
    def __init__(self, path = os.getcwd(), givenOptions = []):
        # Initial values
        self.previous_dir =   os.getcwd()
        self.current_dir =    os.path.abspath(path)
        self.givenOptions =   ''
        self.options =        None
        self.rule_list =      []
        self.alias =          {}
        self.current_rule =   None
        self.executing =      False
        self.executed_rules = set([])
        self.option_files =   set([])

        adagio.logInfo('Directory', None, 
                       'New dir object in ' + self.current_dir)

        configDefaults = adagio.getConfigDefaults(self.current_dir)

        # Compute the project home
        os.chdir(self.current_dir)
        detected_project_home = findProjectDir(configDefaults['project_file'], 
                                               self.current_dir)
        configDefaults['project_home'] = detected_project_home
        os.chdir(self.previous_dir)

        # Compute the relative_basedir (relative path from basedir to
        # project_home
        configDefaults['relative_basedir'] = \
            os.path.relpath(self.current_dir, detected_project_home)

        # Safe parser to store the options, the defaults are loaded here
        self.options = properties.initialConfig(configDefaults)

        #
        # STEP 1: Load the default options from the Rule files
        #
        adagio.LoadDefaults(self.options)

        #
        # STEP 2: Load the ~/.adagiorc if any
        #
        userAdagioConfig = os.path.normpath(os.path.join(os.path.expanduser('~'),
                                                         '.adagiorc'))
        if os.path.isfile(userAdagioConfig):
            # Swallow user file on top of global options, and if trouble, report
            # up
            try:
                (newFiles, b) = properties.loadConfigFile(self.options,
                                                          userAdagioConfig,
                                                          self.alias)
                self.option_files.update(newFiles)
            except ValueError, e:
                print i18n.get('severe_parse_error').format(userAdagioConfig)
                print str(e)
                sys.exit(3)
Example #18
0
def Execute(rule, dirObj):
    """
    Execute the rule in the given directory
    """

    global has_executable

    if has_executable == '':
	has_executable = adagio.findExecutable(rule, dirObj)

    # If the executable is not present, notify and terminate
    if not has_executable:
        print i18n.get('no_executable').format(dirObj.options.get(rule, 'exec'))
        if dirObj.options.get(rule, 'partial') == '0':
            sys.exit(1)
        return

    # Get the files to process, if empty, terminate
    toProcess = rules.getFilesToProcess(rule, dirObj)
    if toProcess == []:
        return


    # Prepare the command to execute
    executable = dirObj.getProperty(rule, 'exec')
    dstDir = dirObj.getProperty(rule, 'dst_dir')
    nupOption = dirObj.getProperty(rule, 'nup')
    # Loop over all source files to process
    for datafile in toProcess:
        adagio.logDebug(rule, dirObj, ' EXEC ' + datafile)

        # If file not found, terminate
        if not os.path.isfile(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Derive the destination file name
        dstFile = os.path.splitext(os.path.basename(datafile))[0] + \
            '-' + nupOption + os.path.splitext(os.path.basename(datafile))[1]
        dstFile = os.path.abspath(os.path.join(dstDir, dstFile))

        # Add the input file to the command
        command = [executable]
        if nupOption != '':
            command.extend(['--outfile', dstFile])
        command.extend(dirObj.getProperty(rule,
                                                'extra_arguments').split())
        command.append(datafile)

        # Perform the execution
        rules.doExecution(rule, dirObj, command, datafile, dstFile,
                            adagio.userLog, adagio.userLog)

    return
Example #19
0
def treatTemplate(config, filename, newOptions, sname, aliasDict, includeChain):
    """
    Process template and parse the required files.

    - Config what you have so far
    - filename file where the template is found
    - NewOptions is the new config
    - sname is the rule name where the template was detected
    - includeChain are the files that are included

    Returns the pair (set of files processed, list of rules detected)
    """

    # Get the pairs in the template rule that are not in the defaults
    # dictionary
    fileItem = [(a, b) for (a, b) in newOptions.items(sname)
                if not a in newOptions.defaults()]

    # There must be a single option with name 'files'
    if len(fileItem) != 1:
        print i18n.get('template_error').format(filename)
        sys.exit(1)

    # The option must have name files
    if fileItem[0][0] != 'files':
        print i18n.get('incorrect_option_in_file').format(fileItem[0][0],
                                                          filename)
        sys.exit(1)

    # Add template rule to the given config to evaluate the files assignment
    templateFiles = setProperty(config, sname, 'files', fileItem[0][1],
                                fileName = filename,
                                createRule = True,
                                createOption = True).split()

    # Remove rule from the original config:
    config.remove_section(sname)

    # Process the template files recursively!
    result = (set([]), [])
    for fname in templateFiles:
        # Get the full path of the template
        if os.path.isabs(fname):
            templateFile = fname
        else:
            templateFile = os.path.abspath(os.path.join(os.path.dirname(filename), fname))

        (a, b) = loadConfigFile(config, 
                                os.path.normpath(templateFile), 
                                aliasDict, includeChain)
        result[0].update(a)
        result[1].extend(b)
    return result
Example #20
0
 def delegate():
     # NOTE: now we're on the ComicForm Application Thread
     self.__current_book = book
     self.__current_page = 0
     self.__current_page_count = page_count
     self.__label.Text = i18n.get("ComicFormScrapingLabel") + book_name
     self.__pbox_panel.set_image(page_image)  # cover image may be None
     self.__progbar.PerformStep()
     self.__progbar.Maximum = self.__progbar.Value + num_remaining
     self.__cancel_button.Text=\
        i18n.get("ComicFormCancelButton").format(sstr(num_remaining))
     self.Update()
 def delegate():
    # NOTE: now we're on the ComicForm Application Thread
    self.__current_book = book
    self.__current_page = 0
    self.__current_page_count = page_count
    self.__label.Text = i18n.get("ComicFormScrapingLabel") + book_name
    self.__pbox_panel.set_image(page_image) # cover image may be None
    self.__progbar.PerformStep()
    self.__progbar.Maximum = self.__progbar.Value + num_remaining
    self.__cancel_button.Text=\
       i18n.get("ComicFormCancelButton").format(sstr(num_remaining))
    self.Update()
Example #22
0
def checkDateFormat(d, f):
    """
    Check if the date d is compliant with the format f. If not, terminate with a
    message.

    Returns the datetime object with the date
    """
    try:
       result = datetime.datetime.strptime(d, f)
    except ValueError, e:
       print i18n.get('date_incorrect_format').format(d, f)
       print str(e)
       sys.exit(1)
Example #23
0
def doShuffle(toProcess, dirObj):
    # Every source file given is processed to know how many permutations will be
    # produced.
    rawFiles = []
    for fname in toProcess:
        # Get the result files
        resultFiles = doGetShuffledFiles(fname)

        # Accumulate the list
        rawFiles.extend(resultFiles)

        # Update the dependencies (apply update to all elements in resultFiles)
        try:
            sources = set([fname])
            sources.update(dirObj.option_files)
            map(lambda x: dependency.update(x, sources), resultFiles)
        except etree.XMLSyntaxError, e:
            print i18n.get('severe_parse_error').format(fName)
            print e
            sys.exit(1)

        # If all the permutation files are up to date, no need to process
        if reduce(lambda x, y: x and y,
                  [dependency.isUpToDate(x) for x in resultFiles]):
            print i18n.get('testexam_no_shuffle_required').format(fname)
            continue

        print i18n.get('testexam_shuffling').format(fname)
        permutations = testshuffle.main(fname, adagio.userLog)

        if permutations == 0:
            print i18n.get('testexam_no_permutations').format(fname)
            sys.exit(1)
Example #24
0
 async def _get(self, ctx: Context, key: str):
     embed: Embed = Embed(title=t("locale.title", k=key))
     embed.add_field(name=t("locale.translation"),
                     value=t(key, prefix=self._bot.command_prefix,
                             command="lang",
                             name=ctx.author.name,
                             name2=f"{ctx.author.name}_2",
                             id=ctx.author.id,
                             id2=str(ctx.author.id)[::-1],
                             locale=get("locale"),
                             locales=get("available_locales"),
                             k=key,
                             role_id=choice(ctx.guild.roles).id))
     await ctx.send(embed=embed)
Example #25
0
   def __build_skip_label(self, skipped_n):
      ''' 
      Builds and returns the 'number skipped' Label for this form.
      'skipped_n' -> the number of books that were skipped. 
      '''

      label = Label()
      label.UseMnemonic = False
      label.Location = Point(10, 30) 
      label.Size = Size(280, 13)
      label.TextAlign = ContentAlignment.MiddleCenter
      label.Text = i18n.get("FinishFormSkippedSingle") if skipped_n==1 else \
         i18n.get("FinishFormSkippedPlural").format(skipped_n)
      return label
Example #26
0
    def __build_skip_label(self, skipped_n):
        ''' 
      Builds and returns the 'number skipped' Label for this form.
      'skipped_n' -> the number of books that were skipped. 
      '''

        label = Label()
        label.UseMnemonic = False
        label.Location = Point(10, 30)
        label.Size = Size(280, 13)
        label.TextAlign = ContentAlignment.MiddleCenter
        label.Text = i18n.get("FinishFormSkippedSingle") if skipped_n==1 else \
           i18n.get("FinishFormSkippedPlural").format(skipped_n)
        return label
 def generate_suite_variables(self):
     robot_buildIn = BuiltIn()
     is_prefer = i18n.get('is_prefer')
     prefer_lang = i18n.get('prefer')
     keys = self._get_all_unique_keys()
     for key in keys:
         robot_buildIn.log('Generate variable for ' + key)
         value = ''
         if is_prefer:
             value = self.translate_message_with_prefer_language(
                 key, prefer_lang)
         else:
             value = self.translate_message(key)
         robot_buildIn.set_suite_variable('${' + key + '}', "" + value)
Example #28
0
def Execute(rule, dirObj):
    """
    Execute the rule in the given directory
    """

    # Get the files to process, if empty, terminate
    toProcess = rules.getFilesToProcess(rule, dirObj)
    if toProcess == []:
        return

    # Every source file given is processed to know how many permutations will be
    # rawFiles contains the list of files produced that need to be processed
    rawFiles = doShuffle(toProcess, dirObj)

    # Prepare the style transformation
    styleFiles = dirObj.getProperty(rule, 'styles')
    styleTransform = xsltproc.createStyleTransform(styleFiles.split())
    if styleTransform == None:
        print i18n.get('no_style_file')
        return

    # Create the dictionary of stylesheet parameters
    styleParams = xsltproc.createParameterDict(rule, dirObj)

    # Create a list with the param dictionaries to use in the different versions
    # to be created.
    paramDict = []
    produceValues = set(dirObj.getProperty(rule, 'produce').split())
    if 'regular' in produceValues:
        # Create the regular version, no additional parameters needed
        paramDict.append(({}, ''))
    if 'solution' in produceValues:
        paramDict.append(({'solutions.include.guide': "'yes'",
                           'adagio.testquestions.include.solutions': "'yes'"},
                          '_solution'))
    if 'pguide' in produceValues:
        paramDict.append(({'solutions.include.guide': "'yes'",
                           'adagio.testquestions.include.solutions': "'yes'",
                           'professorguide.include.guide': "'yes'",
                           'adagio.testquestions.include.id': "'yes'",
                           'adagio.testquestions.include.history': "'yes'"},
                          '_pguide'))

    # Apply all these transformations.
    xsltproc.doTransformations(styleFiles.split(), styleTransform, styleParams,
                               rawFiles, rule, dirObj, paramDict)

    return
Example #29
0
def handle_error(error):
   '''
   Handles the given error object (a python or .net exception) by formatting it
   nicely and then printing it to the debug log.   If the 'app_window' provided
   to the 'install' method was not None, an "unexpected error" message 
   will also be displayed for the user in a modal dialog owned by the
   app_window.
   
   This method should be an application's normal way to handle unexpected
   errors and exceptions.
   '''
   
    
   global __logger, __app_window
   if not __logger:
      return
   
   # if none, do current python exception.  else sstr() the given exception
   if isinstance(error, Exception):
      debug("------------------- PYTHON ERROR ------------------------")
      debug_exc() # a python exception
   else:
      debug("-------------------- .NET ERROR -------------------------")
      debug(utils.sstr(error).replace('\r','')) # a .NET exception 
   
   
   if __app_window:     
      handled = False
      if type(error) == DatabaseConnectionError:  
         # if this is a DatabaseConnectionError, then it is a semi-expected 
         # error that may get a special error message
         if error.get_error_code_s() == "100": # coryhigh: i18n
            MessageBox.Show(__app_window,  # invalid api key
               i18n.get("LogDBErrorApiKeyText").format(error.get_db_name_s()), 
               i18n.get("LogDBErrorTitle"), MessageBoxButtons.OK, 
               MessageBoxIcon.Warning)
            handled = True
         elif error.get_error_code_s() == "107":
            MessageBox.Show(__app_window,  # rate limit reached
               i18n.get("LogDBErrorRateText").format(error.get_db_name_s()), 
               i18n.get("LogDBErrorTitle"), MessageBoxButtons.OK, 
               MessageBoxIcon.Warning)
            handled = True
         elif error.get_error_code_s() == "0":
            MessageBox.Show(__app_window,  # generic 
               i18n.get("LogDBErrorText").format(error.get_db_name_s()), 
               i18n.get("LogDBErrorTitle"), MessageBoxButtons.OK, 
               MessageBoxIcon.Warning)
            handled = True
         
      if not handled:
         # all other errors are considered "unexpected", and handled generically
         result = MessageBox.Show(__app_window, i18n.get("LogErrorText"),
            i18n.get("LogErrorTitle"),  MessageBoxButtons.YesNo, 
            MessageBoxIcon.Error)
      
         if result == DialogResult.Yes:
            save(True)
Example #30
0
def setProperty(config, rule, option, value, fileName = None,
                createRule = None, createOption = None):
    """
    Function that sets the given value for the rule.option in the given
    config and returns the resulting value (after interpolation). createRule
    and createOption is the boolean allowing the creation of both.
    """

    # Obtain the rule prefix
    rulePrefix = rule.split('.')[0]

    # Check if the rule is allowed,
    if (not createRule) and (not config.has_section(rulePrefix)):
        # Rule prefix does not exist in config, and creation is not allowed
        raise ValueError('Rule ' + rulePrefix + ' not allowed.')

    # Create the rule if needed
    if not config.has_section(rule):
        config.add_section(rule)

    # See if the option is already present in the config
    try:
        optionPresent = True
        getProperty(config, rule, option)
    except ConfigParser.NoOptionError:
        optionPresent = False

    # Check if option is allowed
    if (not createOption) and (not optionPresent):
        # Option does not exist in config, and creation is not allowed
        raise ValueError('Option ' + option + ' not allowed.')

    # Insert the option
    config.set(rule, option, value)

    # Register the rule.option also in the __ADAGIO_GIVEN_RULE_NAME
    config.set(_adagio_given_definiton_rule_name,
               rule + '.' + option, value)

    # Get the option just inserted to verify interpolation errors
    try:
        finalValue = config.get(rule, option)
    except (ConfigParser.InterpolationDepthError,
            ConfigParser.InterpolationMissingOptionError), e:
        if fileName != None:
            print i18n.get('severe_parse_error').format(fileName)
        print i18n.get('incorrect_variable_reference').format(value)
        sys.exit(3)
    def __build_gui(self):
        ''' Constructs and initializes the gui for this form. '''

        # 1. --- build each gui component
        self.__ok_button = self.__build_okbutton()
        self.__cancel_button = self.__build_cancel_button()
        self.__restore_button = self.__build_restore_button()
        self.__tabcontrol = self.__build_tabcontrol()

        # 2. -- configure this form, and add all the gui components to it
        self.AutoScaleMode = AutoScaleMode.Font
        self.ClientSize = Size(416, 375)
        self.Text = i18n.get("ConfigFormTitle")

        self.Controls.Add(self.__ok_button)
        self.Controls.Add(self.__cancel_button)
        self.Controls.Add(self.__restore_button)
        self.Controls.Add(self.__tabcontrol)

        # 3. -- define the keyboard focus tab traversal ordering
        self.__ok_button.TabIndex = 0
        self.__cancel_button.TabIndex = 1
        self.__restore_button.TabIndex = 2
        self.__tabcontrol.TabIndex = 3

        self.__fired_update_gui()
Example #32
0
    def __build_gui(self, scraped_n, skipped_n):
        '''
       Constructs and initializes the gui for this form.
      'scraped_n' -> the number of books that were scraped (reported to user)
      'skipped_n' -> the number of books that were skipped (reported to user)
      '''

        # 1. --- build each gui component
        scrape_label = self.__build_scrape_label(scraped_n)
        skip_label = self.__build_skip_label(skipped_n)
        ok = self.__build_okbutton()

        # 2. --- configure this form, and add all the gui components to it
        self.AcceptButton = ok
        self.AutoScaleMode = AutoScaleMode.Font
        self.Text = i18n.get("FinishFormTitle").format(
            Resources.SCRIPT_VERSION)
        self.ClientSize = Size(300, 90)

        self.Controls.Add(scrape_label)
        self.Controls.Add(skip_label)
        self.Controls.Add(ok)

        # 3. --- define the keyboard focus tab traversal ordering
        ok.TabIndex = 0
Example #33
0
   def __build_label(self, series_ref):
      ''' builds and returns the main text label for this form '''

      # 1. compute the best possible full name for the given SeriesRef   
      name_s = series_ref.series_name_s
      publisher_s = series_ref.publisher_s
      vol_year_n = series_ref.volume_year_n
      vol_year_s = sstr(vol_year_n) if vol_year_n > 0 else ''
      fullname_s = ''
      if name_s:
         if publisher_s:
            if vol_year_s:
               fullname_s = "'"+name_s+"' ("+publisher_s+", " + vol_year_s + ")"
            else:
               fullname_s = "'"+name_s+"' (" + publisher_s + ")"
         else:
            fullname_s = "'"+name_s+"'"
            
      
      label = Label()
      label.UseMnemonic = False
      sep = '  ' if len(fullname_s) > 40 else '\n'
      label.Text = i18n.get("IssueFormChooseText").format(fullname_s, sep)
         
      if self.__config.show_covers_b:
         label.Location = Point(218, 20)
         label.Size = Size(480, 40)
      else:
         label.Location = Point(10, 20)
         label.Size = Size(680, 40)
      
      return label
   def __build_label(self, books):
      ''' 
      Builds and returns the Label for this form.
      'books' -> a list of all the comic books being scraped. 
      '''

      plural = len(books) != 1
      
      label = Label()
      label.UseMnemonic = False
      label.AutoSize = True
      label.Location = Point(9, 10)
      label.Size = Size(319, 13)
      label.Text = i18n.get("WelcomeFormTextPlural").format(len(books)) \
         if plural else i18n.get("WelcomeFormTextSingle")
      return label
Example #35
0
def versionToInteger(version):
    """
    Fucntion that given a ??.??.?? version (all digits), produces an integer.
    """

    match = re.match('^(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.(?P<pt>[0-9]+)$',
                     version)
    if not match:
        print i18n.get('incorrect_version_format').version
        sys.exit(3)

    result = 0
    result = 1000000 * int(match.group('major')) + \
        10000 * int(match.group('minor')) + int(match.group('pt'))

    return result
Example #36
0
    def doTest_removeRule(self, initialConditionsFct):
        print('  Open rules dashboard')
        dashboard.open(self.browser)
        dashboard.openAutomation(self.browser)
        ruleNumber = 0

        print('  Get rule table')
        rulesTable = dashboard.automation.waitRulesTableHasNRules(
            self.browser, 1)
        removeButton = dashboard.automation.getRuleRemoveButton(
            rulesTable, ruleNumber)

        initialConditionsFct(rulesTable, ruleNumber)

        print('  Remove rule')
        removeButton.click()
        confirmationModal = modals.waitOkCancelModal(self.browser)
        confirmationModal.ok()

        print('  Expect notification')
        notification.waitText(
            self.browser, notification.Type.Success,
            i18n.get()["modals"]["dashboard"]["sub-windows"]
            ["automation-center"]["ruleDeleted"])
        print('  Check table was updated')
        self.assertTrue(
            tools.waitUntil(
                lambda: dashboard.automation.getRuleNumberInTable(
                    self.browser, rulesTable) == 0, 5))
Example #37
0
    def test_simpleQuery(self):
        print '=== Simple query test ==='
        pluginNumber = 0

        print '  Select query'
        pluginsTable = dashboard.plugins.waitPluginsTableHasNPlugins(
            self.browser, 1)
        tools.waitUntil(lambda: dashboard.plugins.getPluginExtraCommandButton(
            pluginsTable, pluginNumber).is_enabled())
        button = dashboard.plugins.getPluginExtraCommandButton(
            pluginsTable, pluginNumber)
        button.click()

        select = button.find_element_by_xpath(
            ".//following-sibling::ul[@class='dropdown-menu dropdown-extraqueries']"
        )
        select.find_element_by_xpath(
            ".//li/a[@class='btn-extraQuery-simpleCommand']").click()

        notification.waitText(
            self.browser, notification.Type.Success,
            i18n.get()["core"]["plugins"]["extraquery"]["success"].replace(
                "{{extraquery}}",
                i18n.getPlugin("dev-fakePlugin")["extraQueries"]
                ["simpleCommand"]["name"]))
Example #38
0
    def __build_label(self, series_ref):
        """ builds and returns the main text label for this form """

        # 1. compute the best possible full name for the given SeriesRef
        name_s = series_ref.series_name_s
        publisher_s = series_ref.publisher_s
        vol_year_n = series_ref.volume_year_n
        vol_year_s = sstr(vol_year_n) if vol_year_n > 0 else ""
        fullname_s = ""
        if name_s:
            if publisher_s:
                if vol_year_s:
                    fullname_s = "'" + name_s + "' (" + publisher_s + ", " + vol_year_s + ")"
                else:
                    fullname_s = "'" + name_s + "' (" + publisher_s + ")"
            else:
                fullname_s = "'" + name_s + "'"

        label = Label()
        label.UseMnemonic = False
        sep = "  " if len(fullname_s) > 40 else "\n"
        label.Text = i18n.get("IssueFormChooseText").format(fullname_s, sep)

        if self.__config.show_covers_b:
            label.Location = Point(218, 20)
            label.Size = Size(480, 40)
        else:
            label.Location = Point(10, 20)
            label.Size = Size(680, 40)

        return label
Example #39
0
    def test_dataBindingPluginCommandQuery(self):
        print '=== Query with data binding with plugin test ==='
        pluginNumber = 0

        print '  Select query'
        pluginsTable = dashboard.plugins.waitPluginsTableHasNPlugins(
            self.browser, 1)
        tools.waitUntil(lambda: dashboard.plugins.getPluginExtraCommandButton(
            pluginsTable, pluginNumber).is_enabled())
        button = dashboard.plugins.getPluginExtraCommandButton(
            pluginsTable, pluginNumber)
        button.click()

        select = button.find_element_by_xpath(
            ".//following-sibling::ul[@class='dropdown-menu dropdown-extraqueries']"
        )
        select.find_element_by_xpath(
            ".//li/a[@class='btn-extraQuery-dataBindingPluginCommand']").click(
            )

        modal = self.waitExtraQueryParameterModal()
        modal.setEnumField(
            "plugins.dev-fakePlugin:extraQueries.dataBindingPluginCommand.commandData.dynamicSection",
            0)
        modal.ok()

        notification.waitText(
            self.browser, notification.Type.Success,
            i18n.get()["core"]["plugins"]["extraquery"]["success"].replace(
                "{{extraquery}}",
                i18n.getPlugin("dev-fakePlugin")["extraQueries"]
                ["dataBindingPluginCommand"]["name"]))
Example #40
0
    def test_changePluginStateMessageQuery(self):
        print '=== Query of change plugin state test ==='
        pluginNumber = 0

        print '  Select query'
        pluginsTable = dashboard.plugins.waitPluginsTableHasNPlugins(
            self.browser, 1)
        tools.waitUntil(lambda: dashboard.plugins.getPluginExtraCommandButton(
            pluginsTable, pluginNumber).is_enabled())
        button = dashboard.plugins.getPluginExtraCommandButton(
            pluginsTable, pluginNumber)
        button.click()

        select = button.find_element_by_xpath(
            ".//following-sibling::ul[@class='dropdown-menu dropdown-extraqueries']"
        )
        select.find_element_by_xpath(
            ".//li/a[@class='btn-extraQuery-changePluginStateMessage']").click(
            )

        modal = self.waitExtraQueryParameterModal()
        modal.setTextField(
            "plugins.dev-fakePlugin:extraQueries.changePluginStateMessage.commandData.newStateMessage",
            "message associated to plugin state")
        modal.ok()

        notification.waitText(
            self.browser, notification.Type.Success,
            i18n.get()["core"]["plugins"]["extraquery"]["success"].replace(
                "{{extraquery}}",
                i18n.getPlugin("dev-fakePlugin")["extraQueries"]
                ["changePluginStateMessage"]["name"]))
Example #41
0
    def __key_was_released(self, sender, args):
        """ Called whenever the user releases any key on this form. """

        # unhighlight the skip button bold whenever the user releases control key
        if args.KeyCode == Keys.ControlKey:
            self.__pressing_controlkey = False
            self.__skip_button.Text = i18n.get("IssueFormSkip")
Example #42
0
    def __was_deactivated(self, sender, args):
        """ Called whenever this form gets deactivated, for any reason """

        # unhighlight the skip button bold whenever we deactivate
        if self.__pressing_controlkey:
            self.__pressing_controlkey = False
            self.__skip_button.Text = i18n.get("IssueFormSkip")
Example #43
0
    def test_editStoppedRule(self):
        print('=== Edit of a stopped rule test ===')
        ruleNumber = 0

        # Edit the first rule
        print('Open the rule edit modal')
        rulesTable = dashboard.automation.waitRulesTableHasNRules(
            self.browser, 1)
        tools.waitUntil(lambda: dashboard.automation.getRuleEditButton(
            rulesTable, ruleNumber).is_enabled())
        dashboard.automation.getRuleEditButton(rulesTable, ruleNumber).click()

        print('Change rule description')
        ruleNewDescription = "This is the new rule description"
        editRuleModal = dashboard.automation.waitEditRuleModal(self.browser)
        editRuleModal.setRuleDescription(ruleNewDescription)
        editRuleModal.ok()

        print('Check modified rule')
        notification.waitText(
            self.browser, notification.Type.Success,
            i18n.get()["modals"]["dashboard"]["sub-windows"]
            ["automation-center"]["ruleSuccessfullyUpdated"])

        rulesTable = dashboard.automation.waitRulesTableHasNRules(
            self.browser, 1)
        ruleDatas = dashboard.automation.getRuleDatas(rulesTable, ruleNumber)
        tools.waitUntil(lambda: len(ruleDatas[1].text) > 0)
        self.assertEqual(ruleDatas[1].text, ruleNewDescription)
        self.assertEqual(
            dashboard.automation.getRuleState(rulesTable, ruleNumber),
            dashboard.automation.RuleState.Stopped)
        self.assertFalse(
            dashboard.automation.getRuleAutoStartState(rulesTable, ruleNumber))
Example #44
0
    def __key_was_pressed(self, sender, args):
        """ Called whenever the user presses any key on this form. """

        # highlight the skip button whenever the user presses control key
        if args.KeyCode == Keys.ControlKey and not self.__pressing_controlkey:
            self.__pressing_controlkey = True
            self.__skip_button.Text = "- " + i18n.get("IssueFormSkip") + " -"
Example #45
0
    def __key_was_pressed(self, sender, args):
        ''' Called whenever the user presses any key on this form. '''

        # highlight the skip button whenever the user presses control key
        if args.KeyCode == Keys.ControlKey and not self.__pressing_controlkey:
            self.__pressing_controlkey = True
            self.__skip_button.Text = "- " + i18n.get("SeriesFormSkip") + " -"
   def __build_gui(self):
      ''' Constructs and initializes the gui for this form. '''
      
      # 1. --- build each gui component
      self.__ok_button = self.__build_okbutton()
      self.__cancel_button = self.__build_cancel_button()
      self.__restore_button = self.__build_restore_button()
      self.__tabcontrol = self.__build_tabcontrol()
         
      # 2. -- configure this form, and add all the gui components to it
      self.AutoScaleMode = AutoScaleMode.Font
      self.ClientSize = Size(416, 375)
      self.Text = i18n.get("ConfigFormTitle")
   
      self.Controls.Add(self.__ok_button)                                     
      self.Controls.Add(self.__cancel_button)                                 
      self.Controls.Add(self.__restore_button)                                
      self.Controls.Add(self.__tabcontrol)                             
      
      # 3. -- define the keyboard focus tab traversal ordering
      self.__ok_button.TabIndex = 0                                        
      self.__cancel_button.TabIndex = 1                                    
      self.__restore_button.TabIndex = 2
      self.__tabcontrol.TabIndex = 3                                 

      self.__fired_update_gui()  
Example #47
0
    def __was_deactivated(self, sender, args):
        ''' Called whenever this form gets deactivated, for any reason '''

        # unhighlight the skip button bold whenever we deactivate
        if self.__pressing_controlkey:
            self.__pressing_controlkey = False
            self.__skip_button.Text = i18n.get("SeriesFormSkip")
Example #48
0
    def __key_was_released(self, sender, args):
        ''' Called whenever the user releases any key on this form. '''

        # unhighlight the skip button bold whenever the user releases control key
        if args.KeyCode == Keys.ControlKey:
            self.__pressing_controlkey = False
            self.__skip_button.Text = i18n.get("SeriesFormSkip")
Example #49
0
    def test_asyncEQwithProgressionQuery(self):
        print '=== Query with progress following test ==='
        pluginNumber = 0

        print '  Select query'
        pluginsTable = dashboard.plugins.waitPluginsTableHasNPlugins(
            self.browser, 1)
        tools.waitUntil(lambda: dashboard.plugins.getPluginExtraCommandButton(
            pluginsTable, pluginNumber).is_enabled())
        button = dashboard.plugins.getPluginExtraCommandButton(
            pluginsTable, pluginNumber)
        button.click()

        select = button.find_element_by_xpath(
            ".//following-sibling::ul[@class='dropdown-menu dropdown-extraqueries']"
        )
        select.find_element_by_xpath(
            ".//li/a[@class='btn-extraQuery-asyncEQwithProgression']").click()

        modal = self.waitExtraQueryParameterModal()
        modal.setFileField(
            "plugins.dev-fakePlugin:extraQueries.asyncEQwithProgression.commandData.fileContent",
            __file__)
        modal.ok()

        notification.waitText(
            self.browser, notification.Type.Success,
            i18n.get()["core"]["plugins"]["extraquery"]["success"].replace(
                "{{extraquery}}",
                i18n.getPlugin("dev-fakePlugin")["extraQueries"]
                ["asyncEQwithProgression"]["name"]), 20)
Example #50
0
def checkCreatedPluginSequence(test, pluginInstanceName, pluginType,
                               hasExtraCommand, hasLog):
    """ Check successfull plugin creation all-in-one sequence """

    print '  Check notification'
    notification.waitText(
        test.browser, notification.Type.Success,
        i18n.get()["modals"]["configure-plugin"]["pluginSuccessfullyCreated"])

    print '  Check plugins table'
    pluginsTable = waitPluginsTableHasNPlugins(test.browser, 1)

    pluginNumber = 0

    test.assertEqual(len(getPluginDatas(pluginsTable, pluginNumber)), 5)
    test.assertEqual(getPluginName(pluginsTable, pluginNumber),
                     pluginInstanceName)
    test.assertEqual(
        getPluginType(pluginsTable, pluginNumber).lstrip(),
        i18n.getPlugin(pluginType)["name"])
    test.assertTrue(getPluginAutoStartState(pluginsTable, pluginNumber))

    buttons = getPluginButtons(pluginsTable, pluginNumber)
    expectedButtonCount = 3 + (1 if hasExtraCommand else 0) + (1 if hasLog else
                                                               0)
    test.assertEqual(len(buttons), expectedButtonCount)

    buttonIndex = 0
    startStopButton = getPluginStartStopButton(pluginsTable, pluginNumber)
    test.assertEqual(startStopButton, buttons[buttonIndex])
    tools.waitUntil(
        lambda: "btn-warning" in startStopButton.get_attribute("class"))
    buttonIndex += 1

    configureButton = getPluginConfigureButton(pluginsTable, pluginNumber)
    test.assertEqual(configureButton, buttons[buttonIndex])
    test.assertIn("btn-primary", configureButton.get_attribute("class"))
    buttonIndex += 1

    if hasExtraCommand:
        extraCommandButton = getPluginExtraCommandButton(
            pluginsTable, pluginNumber)
        test.assertEqual(extraCommandButton, buttons[buttonIndex])
        test.assertIn("btn-success", extraCommandButton.get_attribute("class"))
        buttonIndex += 1

    if hasLog:
        logButton = getPluginLogButton(pluginsTable, pluginNumber)
        test.assertEqual(logButton, buttons[buttonIndex])
        test.assertIn("btn-info", logButton.get_attribute("class"))
        buttonIndex += 1

    removeButton = getPluginRemoveButton(pluginsTable, pluginNumber)
    test.assertEqual(removeButton, buttons[buttonIndex])
    test.assertIn("btn-danger", removeButton.get_attribute("class"))
    buttonIndex += 1

    WebDriverWait(test.browser, 20).until(lambda browser: getPluginState(
        pluginsTable, pluginNumber) == PluginState.Running)
Example #51
0
 def __build_label(self, search_terms_s, num_matches_n):
    ''' 
    Builds and return the text label for this form.
    'search_terms_s' -> user's search string that was used to find series
    'num_matches_n' -> number of series (table rows) the user's search matched
    '''
    
    label = Label()
    label.UseMnemonic = False
    label.Location = Point(10, 20)
    label.Size = Size(480, 40)
    if num_matches_n > 1:
       label.Text = i18n.get("SeriesFormChooseText")\
          .format(search_terms_s, num_matches_n )
    else:
       label.Text = i18n.get("SeriesFormConfirmText").format(search_terms_s)
    return label
Example #52
0
    def __build_okbutton(self):
        ''' builds and returns the ok button for this form '''

        button = Button()
        button.DialogResult = DialogResult.OK
        button.Location = Point(15, 362)
        button.Size = Size(90, 24)
        button.Text = i18n.get("SeriesFormOK")
        return button
    def __build_label(self):
        ''' builds and returns the text label for this form '''

        label = Label()
        label.UseMnemonic = False
        label.Location = Point(10, 110 if self.__fail_label_is_visible else 10)
        label.Size = Size(415, 20)
        label.Text = i18n.get("SearchFormText")
        return label
Example #54
0
def waitAddPageModal(browser):
    modal = WebDriverWait(browser, 10).until(
        Condition.visibility_of_element_located(
            (By.XPATH, ".//div[@id='modify-page-modal']")))
    if modal.find_element_by_xpath(
            ".//h4[@class='modal-title']").text == i18n.get(
            )["modals"]["modify-page"]["createNewPageTitle"]:
        return AddPageModal(modal)
    assert False
Example #55
0
    def __build_skipbutton(self):
        ''' builds and return the skip button for this form '''

        button = Button()
        button.DialogResult = DialogResult.Ignore
        button.Location = Point(110, 362)
        button.Size = Size(90, 24)
        button.Text = i18n.get("SeriesFormSkip")
        return button
Example #56
0
 def __build_backbutton(self):
    ''' builds and returns the back button for this form '''
    
    button = Button()
    button.DialogResult = DialogResult.Retry
    button.Location = Point(595, 362)
    button.Size = Size(125, 24)
    button.Text = i18n.get("IssueFormGoBack")
    return button
Example #57
0
 async def lang(self, ctx: Context):
     if ctx.invoked_subcommand:
         return
     embed: Embed = Embed(title=t("locale.language"))
     embed.add_field(name=t("locale.current"),
                     value=f"**{get('locale')}** {t('flag')}")
     embed.add_field(name=t("locale.available"),
                     value=", ".join(get("available_locales")))
     await ctx.send(embed=embed)
    def __build_restore_button(self):
        ''' builds and returns the restore button for this form '''

        button = Button()
        button.Click += self.__fired_restore_defaults
        button.Location = Point(10, 343)
        button.Size = Size(170, 23)
        button.Text = i18n.get("ConfigFormRestore")
        return button
    def __build_cancel_button(self):
        ''' builds and returns the cancel button for this form '''

        button = Button()
        button.DialogResult = DialogResult.Cancel
        button.Location = Point(315, 343)
        button.Size = Size(90, 23)
        button.Text = i18n.get("ConfigFormCancel")
        return button