Example #1
0
 inline void ClearData()
 {
     for(UINT i=0; i<windowData.Num(); i++)
         windowData[i].strClass.Clear();
     windowData.Clear();
     adminWindows.Clear();
     opposingBitWindows.Clear();
 }
Example #2
0
File: XT.cpp Project: robessog/OBS
void STDCALL TraceCrashEnd()
{
    String strStackTrace = TEXT("\r\nException Fault - Stack Trace:");

    for(unsigned int i=0; i<TraceFuncList.Num(); i++)
    {
        if(i) strStackTrace << TEXT(" -> ");
        if(!(i%10)) strStackTrace << TEXT("\r\n    ");
        strStackTrace << TraceFuncList[i];
    }

    if(TraceFuncList.Num() == MAX_STACK_TRACE)
        strStackTrace << TEXT(" -> ...");

    String strOut = FormattedString(TEXT("%s\r\n"), strStackTrace.Array());

    OpenLogFile();
    LogFile.WriteAsUTF8(strOut, strOut.Length());
    LogFile.WriteAsUTF8(TEXT("\r\n"));
    CloseLogFile();

    OSMessageBox(TEXT("Error: Exception fault - More info in the log file.\r\n\r\nMake sure you're using the latest verison, otherwise send your log to [email protected]"));

    TraceFuncList.Clear();
    CriticalExit();
}
Example #3
0
size_t
StringList::AutoComplete (const char *s, StringList &matches, size_t &exact_idx) const
{
    matches.Clear();
    exact_idx = SIZE_MAX;
    if (s && s[0])
    {
        const size_t s_len = strlen (s);
        const size_t num_strings = m_strings.size();
        
        for (size_t i=0; i<num_strings; ++i)
        {
            if (m_strings[i].find(s) == 0)
            {
                if (exact_idx == SIZE_MAX && m_strings[i].size() == s_len)
                    exact_idx = matches.GetSize();
                matches.AppendString (m_strings[i]);
            }
        }
    }
    else
    {
        // No string, so it matches everything
        matches = *this;
    }
    return matches.GetSize();
}
Example #4
0
size_t OptionValue::AutoComplete(CommandInterpreter &interpreter, const char *s,
                                 int match_start_point, int max_return_elements,
                                 bool &word_complete, StringList &matches) {
  word_complete = false;
  matches.Clear();
  return matches.GetSize();
}
int
CommandObjectRegexCommand::HandleCompletion (Args &input,
                                             int &cursor_index,
                                             int &cursor_char_position,
                                             int match_start_point,
                                             int max_return_elements,
                                             bool &word_complete,
                                             StringList &matches)
{
    if (m_completion_type_mask)
    {
        std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position);
        CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
                                                             m_completion_type_mask,
                                                             completion_str.c_str(),
                                                             match_start_point,
                                                             max_return_elements,
                                                             nullptr,
                                                             word_complete,
                                                             matches);
        return matches.GetSize();
    }
    else
    {
        matches.Clear();
        word_complete = false;
    }
    return 0;
}
size_t
OptionValueEnumeration::AutoComplete (CommandInterpreter &interpreter,
                                      const char *s,
                                      int match_start_point,
                                      int max_return_elements,
                                      bool &word_complete,
                                      StringList &matches)
{
    word_complete = false;
    matches.Clear();
    
    const uint32_t num_enumerators = m_enumerations.GetSize();
    if (s && s[0])
    {
        const size_t s_len = strlen(s);
        for (size_t i=0; i<num_enumerators; ++i)
        {
            const char *name = m_enumerations.GetCStringAtIndex(i);
            if (::strncmp(s, name, s_len) == 0)
                matches.AppendString(name);
        }
    }
    else
    {
        // only suggest "true" or "false" by default
        for (size_t i=0; i<num_enumerators; ++i)
            matches.AppendString(m_enumerations.GetCStringAtIndex(i));
    }
    return matches.GetSize();
}
Example #7
0
 inline void ClearData()
 {
     for(UINT i=0; i<windowData.Num(); i++)
     {
         windowData[i].strClass.Clear();
         windowData[i].strExecutable.Clear();
     }
     windowData.Clear();
     adminWindows.Clear();
 }
int CommandObjectProxy::HandleArgumentCompletion(
    Args &input, int &cursor_index, int &cursor_char_position,
    OptionElementVector &opt_element_vector, int match_start_point,
    int max_return_elements, bool &word_complete, StringList &matches) {
  CommandObject *proxy_command = GetProxyCommandObject();
  if (proxy_command)
    return proxy_command->HandleArgumentCompletion(
        input, cursor_index, cursor_char_position, opt_element_vector,
        match_start_point, max_return_elements, word_complete, matches);
  matches.Clear();
  return 0;
}
Example #9
0
File: REPL.cpp Project: kraj/lldb
int REPL::IOHandlerComplete(IOHandler &io_handler, const char *current_line,
                            const char *cursor, const char *last_char,
                            int skip_first_n_matches, int max_matches,
                            StringList &matches) {
  matches.Clear();

  llvm::StringRef line(current_line, cursor - current_line);

  // Complete an LLDB command if the first character is a colon...
  if (!line.empty() && line[0] == ':') {
    Debugger &debugger = m_target.GetDebugger();

    // auto complete LLDB commands
    const char *lldb_current_line = line.substr(1).data();
    return debugger.GetCommandInterpreter().HandleCompletion(
        lldb_current_line, cursor, last_char, skip_first_n_matches, max_matches,
        matches);
  }

  // Strip spaces from the line and see if we had only spaces
  line = line.ltrim();
  if (line.empty()) {
    // Only spaces on this line, so just indent
    matches.AppendString(m_indent_str);
    return 1;
  }

  std::string current_code;
  current_code.append(m_code.CopyList());

  IOHandlerEditline &editline = static_cast<IOHandlerEditline &>(io_handler);
  const StringList *current_lines = editline.GetCurrentLines();
  if (current_lines) {
    const uint32_t current_line_idx = editline.GetCurrentLineIndex();

    if (current_line_idx < current_lines->GetSize()) {
      for (uint32_t i = 0; i < current_line_idx; ++i) {
        const char *line_cstr = current_lines->GetStringAtIndex(i);
        if (line_cstr) {
          current_code.append("\n");
          current_code.append(line_cstr);
        }
      }
    }
  }

  if (cursor > current_line) {
    current_code.append("\n");
    current_code.append(current_line, cursor - current_line);
  }

  return CompleteCode(current_code, matches);
}
Example #10
0
File: For.cpp Project: weinhold/Ham
StringList
For::Evaluate(EvaluationContext& context)
{
	// get the loop variable -- we ignore all but the first element of the
	// variable list
	const StringList& variables = fVariable->Evaluate(context);
	if (variables.IsEmpty())
		return StringList::False();

	// look for a local variable
	StringList* variableValue = context.LocalScope()->Lookup(variables.Head());
	if (variableValue == NULL) {
		// no local variable -- check for a global one
		variableValue = context.GlobalVariables()->Lookup(variables.Head());
		if (variableValue == NULL) {
			// no existing global variable either -- create one
			variableValue = &context.GlobalVariables()->LookupOrCreate(
				variables.Head());
		}
	}

	// perform the for loop
	StringList result;
	const StringList& list = fList->Evaluate(context);
	for (StringList::Iterator it = list.GetIterator(); it.HasNext();) {
		// assign the variable
		variableValue->Clear();
		variableValue->Append(it.Next());

		// execute the block
		result = fBlock->Evaluate(context);

		// handle jump conditions
		switch (context.GetJumpCondition()) {
			case JUMP_CONDITION_NONE:
				break;
			case JUMP_CONDITION_BREAK:
				context.SetJumpCondition(JUMP_CONDITION_NONE);
				return result;
			case JUMP_CONDITION_CONTINUE:
				context.SetJumpCondition(JUMP_CONDITION_NONE);
				break;
			case JUMP_CONDITION_RETURN:
			case JUMP_CONDITION_JUMP_TO_EOF:
			case JUMP_CONDITION_EXIT:
				return result;
		}
	}

	return result;
}
Example #11
0
void  XElement::GetStringList(CTSTR lpName, StringList &stringList) const
{
    assert(lpName);

    stringList.Clear();

    for(DWORD i=0; i<SubItems.Num(); i++)
    {
        if(!SubItems[i]->IsData()) continue;

        XDataItem *item = static_cast<XDataItem*>(SubItems[i]);
        if(item->strName.CompareI(lpName))
            stringList << item->strData;
    }
}
size_t
OptionValueUUID::AutoComplete (CommandInterpreter &interpreter,
                               const char *s,
                               int match_start_point,
                               int max_return_elements,
                               bool &word_complete,
                               StringList &matches)
{
    word_complete = false;
    matches.Clear();
    ExecutionContext exe_ctx(interpreter.GetExecutionContext());
    Target *target = exe_ctx.GetTargetPtr();
    if (target)
    {
        const size_t num_modules = target->GetImages().GetSize();
        if (num_modules > 0)
        {
            UUID::ValueType uuid_bytes;
            const size_t num_bytes_decoded = UUID::DecodeUUIDBytesFromCString(s, uuid_bytes, NULL);
            for (size_t i=0; i<num_modules; ++i)
            {
                ModuleSP module_sp (target->GetImages().GetModuleAtIndex(i));
                if (module_sp)
                {
                    const UUID &module_uuid = module_sp->GetUUID();
                    if (module_uuid.IsValid())
                    {
                        bool add_uuid = false;
                        if (num_bytes_decoded == 0)
                            add_uuid = true;
                        else
                            add_uuid = ::memcmp(module_uuid.GetBytes(), uuid_bytes, num_bytes_decoded) == 0;
                        if (add_uuid)
                        {
                            std::string uuid_str;
                            uuid_str = module_uuid.GetAsString();
                            if (!uuid_str.empty())
                                matches.AppendString(uuid_str.c_str());
                        }
                    }
                }
            }
        }
    }
    return matches.GetSize();
}
Example #13
0
size_t
Host::GetEnvironment(StringList &env)
{
    // The environment block on Windows is a contiguous buffer of NULL terminated strings,
    // where the end of the environment block is indicated by two consecutive NULLs.
    LPCH environment_block = ::GetEnvironmentStrings();
    env.Clear();
    while (*environment_block != '\0')
    {
        llvm::StringRef current_var(environment_block);
        if (current_var[0] != '=')
            env.AppendString(current_var);

        environment_block += current_var.size()+1;
    }
    return env.GetSize();
}
Example #14
0
size_t
OptionValueBoolean::AutoComplete (CommandInterpreter &interpreter,
                                  const char *s,
                                  int match_start_point,
                                  int max_return_elements,
                                  bool &word_complete,
                                  StringList &matches)
{
    word_complete = false;
    matches.Clear();
    struct StringEntry {
        const char *string;
        const size_t length;
    };
    static const StringEntry g_autocomplete_entries[] =
    {
        { "true" , 4 },
        { "false", 5 },
        { "on"   , 2 },
        { "off"  , 3 },
        { "yes"  , 3 },
        { "no"   , 2 },
        { "1"    , 1 },
        { "0"    , 1 },
    };
    const size_t k_num_autocomplete_entries = llvm::array_lengthof(g_autocomplete_entries);
    
    if (s && s[0])
    {
        const size_t s_len = strlen(s);
        for (size_t i=0; i<k_num_autocomplete_entries; ++i)
        {
            if (s_len <= g_autocomplete_entries[i].length)
                if (::strncasecmp(s, g_autocomplete_entries[i].string, s_len) == 0)
                    matches.AppendString(g_autocomplete_entries[i].string);
        }
    }
    else
    {
        // only suggest "true" or "false" by default
        for (size_t i=0; i<2; ++i)
            matches.AppendString(g_autocomplete_entries[i].string);
    }
    return matches.GetSize();
}
Example #15
0
size_t
OptionValueFileSpec::AutoComplete (CommandInterpreter &interpreter,
                                   const char *s,
                                   int match_start_point,
                                   int max_return_elements,
                                   bool &word_complete,
                                   StringList &matches)
{
    word_complete = false;
    matches.Clear();
    CommandCompletions::InvokeCommonCompletionCallbacks (interpreter,
                                                         m_completion_mask,
                                                         s,
                                                         match_start_point,
                                                         max_return_elements,
                                                         NULL,
                                                         word_complete,
                                                         matches);
    return matches.GetSize();
}
Example #16
0
size_t
OptionValueArch::AutoComplete (CommandInterpreter &interpreter,
                                   const char *s,
                                   int match_start_point,
                                   int max_return_elements,
                                   bool &word_complete,
                                   StringList &matches)
{
    word_complete = false;
    matches.Clear();
    CommandCompletions::InvokeCommonCompletionCallbacks (interpreter,
                                                         CommandCompletions::eArchitectureCompletion,
                                                         s,
                                                         match_start_point,
                                                         max_return_elements,
                                                         nullptr,
                                                         word_complete,
                                                         matches);
    return matches.GetSize();
}
Example #17
0
File: OBS.cpp Project: SeargeDP/OBS
void OBS::GetProfiles(StringList &profileList)
{
    String strProfilesWildcard;
    OSFindData ofd;
    HANDLE hFind;

    profileList.Clear();

    strProfilesWildcard << lpAppDataPath << TEXT("\\profiles\\*.ini");

    if(hFind = OSFindFirstFile(strProfilesWildcard, ofd))
    {
        do
        {
            if(ofd.bDirectory) continue;
            profileList << GetPathWithoutExtension(ofd.fileName);
        } while(OSFindNextFile(hFind, ofd));

        OSFindClose(hFind);
    }
}
Example #18
0
size_t StringList::AutoComplete(llvm::StringRef s, StringList &matches,
                                size_t &exact_idx) const {
  matches.Clear();
  exact_idx = SIZE_MAX;
  if (s.empty()) {
    // No string, so it matches everything
    matches = *this;
    return matches.GetSize();
  }

  const size_t s_len = s.size();
  const size_t num_strings = m_strings.size();

  for (size_t i = 0; i < num_strings; ++i) {
    if (m_strings[i].find(s) == 0) {
      if (exact_idx == SIZE_MAX && m_strings[i].size() == s_len)
        exact_idx = matches.GetSize();
      matches.AppendString(m_strings[i]);
    }
  }
  return matches.GetSize();
}
Example #19
0
bool
CommandObjectHelp::Execute (Args& command, CommandReturnObject &result)
{
    CommandObject::CommandMap::iterator pos;
    CommandObject *cmd_obj;
    const int argc = command.GetArgumentCount ();
    
    // 'help' doesn't take any options or arguments, other than command names.  If argc is 0, we show the user
    // all commands and aliases.  Otherwise every argument must be the name of a command or a sub-command.
    if (argc == 0)
    {
        result.SetStatus (eReturnStatusSuccessFinishNoResult);
        m_interpreter.GetHelp (result);  // General help, for ALL commands.
    }
    else
    {
        // Get command object for the first command argument. Only search built-in command dictionary.
        StringList matches;
        cmd_obj = m_interpreter.GetCommandObject (command.GetArgumentAtIndex (0), &matches);
        bool is_alias_command = m_interpreter.AliasExists (command.GetArgumentAtIndex (0));
        std::string alias_name = command.GetArgumentAtIndex(0);
        
        if (cmd_obj != NULL)
        {
            StringList matches;
            bool all_okay = true;
            CommandObject *sub_cmd_obj = cmd_obj;
            // Loop down through sub_command dictionaries until we find the command object that corresponds
            // to the help command entered.
            for (int i = 1; i < argc && all_okay; ++i)
            {
                std::string sub_command = command.GetArgumentAtIndex(i);
                matches.Clear();
                if (! sub_cmd_obj->IsMultiwordObject ())
                {
                    all_okay = false;
                }
                else
                {
                    CommandObject *found_cmd;
                    found_cmd = ((CommandObjectMultiword *) sub_cmd_obj)->GetSubcommandObject(sub_command.c_str(), 
                                                                                              &matches);
                    if (found_cmd == NULL)
                        all_okay = false;
                    else if (matches.GetSize() > 1)
                        all_okay = false;
                    else
                        sub_cmd_obj = found_cmd;
                }
            }
            
            if (!all_okay || (sub_cmd_obj == NULL))
            {
                std::string cmd_string;
                command.GetCommandString (cmd_string);
                if (matches.GetSize() < 2)
                {
                    result.AppendErrorWithFormat("'%s' is not a known command.\n"
                                                 "Try 'help' to see a current list of commands.\n",
                                                 cmd_string.c_str());
                }
                else 
                {
                    StreamString s;
                    s.Printf ("ambiguous command %s", cmd_string.c_str());
                    size_t num_matches = matches.GetSize();
                    for (size_t match_idx = 0; match_idx < num_matches; match_idx++)
                    {
                        s.Printf ("\n\t%s", matches.GetStringAtIndex(match_idx));
                    }
                    s.Printf ("\n");
                    result.AppendError(s.GetData());
                }

                result.SetStatus (eReturnStatusFailed);
            }
            else
            {
                Stream &output_strm = result.GetOutputStream();
                if (sub_cmd_obj->GetOptions() != NULL)
                {
                    if (sub_cmd_obj->WantsRawCommandString())
                    {
                        std::string help_text (sub_cmd_obj->GetHelp());
                        help_text.append ("  This command takes 'raw' input (no need to quote stuff).");
                        m_interpreter.OutputFormattedHelpText (output_strm, "", "", help_text.c_str(), 1);
                    }
                    else
                        m_interpreter.OutputFormattedHelpText (output_strm, "", "", sub_cmd_obj->GetHelp(), 1);
                    output_strm.Printf ("\nSyntax: %s\n", sub_cmd_obj->GetSyntax());
                    sub_cmd_obj->GetOptions()->GenerateOptionUsage (m_interpreter, output_strm, sub_cmd_obj);
                    const char *long_help = sub_cmd_obj->GetHelpLong();
                    if ((long_help != NULL)
                        && (strlen (long_help) > 0))
                        output_strm.Printf ("\n%s", long_help);
                    // Mark this help command with a success status.
                    if (sub_cmd_obj->WantsRawCommandString())
                    {
                        m_interpreter.OutputFormattedHelpText (output_strm, "", "", "\nIMPORTANT NOTE:  Because this command takes 'raw' input, if you use any command options you must use ' -- ' between the end of the command options and the beginning of the raw input.", 1);
                    }
                    result.SetStatus (eReturnStatusSuccessFinishNoResult);
                }
                else if (sub_cmd_obj->IsMultiwordObject())
                {
                    if (sub_cmd_obj->WantsRawCommandString())
                    {
                        std::string help_text (sub_cmd_obj->GetHelp());
                        help_text.append ("  This command takes 'raw' input (no need to quote stuff).");
                        m_interpreter.OutputFormattedHelpText (output_strm, "", "", help_text.c_str(), 1);
                    }
                    else
                        m_interpreter.OutputFormattedHelpText (output_strm, "", "", sub_cmd_obj->GetHelp(), 1);
                    ((CommandObjectMultiword *) sub_cmd_obj)->GenerateHelpText (result);
                }
                else
                {
                    const char *long_help = sub_cmd_obj->GetHelpLong();
                    if ((long_help != NULL)
                        && (strlen (long_help) > 0))
                        output_strm.Printf ("\n%s", long_help);
                    else if (sub_cmd_obj->WantsRawCommandString())
                    {
                        std::string help_text (sub_cmd_obj->GetHelp());
                        help_text.append ("  This command takes 'raw' input (no need to quote stuff).");
                        m_interpreter.OutputFormattedHelpText (output_strm, "", "", help_text.c_str(), 1);
                    }
                    else
                        m_interpreter.OutputFormattedHelpText (output_strm, "", "", sub_cmd_obj->GetHelp(), 1);
                    output_strm.Printf ("\nSyntax: %s\n", sub_cmd_obj->GetSyntax());
                    // Mark this help command with a success status.
                    result.SetStatus (eReturnStatusSuccessFinishNoResult);
                }
            }
            
            if (is_alias_command)
            {
                StreamString sstr;
                m_interpreter.GetAliasHelp (alias_name.c_str(), cmd_obj->GetCommandName(), sstr);
                result.GetOutputStream().Printf ("\n'%s' is an abbreviation for %s\n", alias_name.c_str(), sstr.GetData());
            }
        }
        else if (matches.GetSize() > 0)
        {
            Stream &output_strm = result.GetOutputStream();
            output_strm.Printf("Help requested with ambiguous command name, possible completions:\n");
            const uint32_t match_count = matches.GetSize();
            for (uint32_t i = 0; i < match_count; i++)
            {
                output_strm.Printf("\t%s\n", matches.GetStringAtIndex(i));
            }
        }
        else
        {
            // Maybe the user is asking for help about a command argument rather than a command.
            const CommandArgumentType arg_type = CommandObject::LookupArgumentName (command.GetArgumentAtIndex (0));
            if (arg_type != eArgTypeLastArg)
            {
                Stream &output_strm = result.GetOutputStream ();
                CommandObject::GetArgumentHelp (output_strm, arg_type, m_interpreter);
                result.SetStatus (eReturnStatusSuccessFinishNoResult);
            }
            else
            {
                result.AppendErrorWithFormat 
                    ("'%s' is not a known command.\nTry 'help' to see a current list of commands.\n",
                     command.GetArgumentAtIndex(0));
                result.SetStatus (eReturnStatusFailed);
            }
        }
    }
    
    return result.Succeeded();
}
static int DiskFilesOrDirectories(const llvm::Twine &partial_name,
                                  bool only_directories, StringList &matches,
                                  TildeExpressionResolver &Resolver) {
  matches.Clear();

  llvm::SmallString<256> CompletionBuffer;
  llvm::SmallString<256> Storage;
  partial_name.toVector(CompletionBuffer);

  if (CompletionBuffer.size() >= PATH_MAX)
    return matches.GetSize();

  namespace path = llvm::sys::path;

  llvm::StringRef SearchDir;
  llvm::StringRef PartialItem;

  if (CompletionBuffer.startswith("~")) {
    llvm::StringRef Buffer(CompletionBuffer);
    size_t FirstSep =
        Buffer.find_if([](char c) { return path::is_separator(c); });

    llvm::StringRef Username = Buffer.take_front(FirstSep);
    llvm::StringRef Remainder;
    if (FirstSep != llvm::StringRef::npos)
      Remainder = Buffer.drop_front(FirstSep + 1);

    llvm::SmallString<256> Resolved;
    if (!Resolver.ResolveExact(Username, Resolved)) {
      // We couldn't resolve it as a full username.  If there were no slashes
      // then this might be a partial username.   We try to resolve it as such
      // but after that, we're done regardless of any matches.
      if (FirstSep == llvm::StringRef::npos) {
        llvm::StringSet<> MatchSet;
        Resolver.ResolvePartial(Username, MatchSet);
        for (const auto &S : MatchSet) {
          Resolved = S.getKey();
          path::append(Resolved, path::get_separator());
          matches.AppendString(Resolved);
        }
      }
      return matches.GetSize();
    }

    // If there was no trailing slash, then we're done as soon as we resolve
    // the expression to the correct directory.  Otherwise we need to continue
    // looking for matches within that directory.
    if (FirstSep == llvm::StringRef::npos) {
      // Make sure it ends with a separator.
      path::append(CompletionBuffer, path::get_separator());
      matches.AppendString(CompletionBuffer);
      return matches.GetSize();
    }

    // We want to keep the form the user typed, so we special case this to
    // search in the fully resolved directory, but CompletionBuffer keeps the
    // unmodified form that the user typed.
    Storage = Resolved;
    llvm::StringRef RemainderDir = path::parent_path(Remainder);
    if (!RemainderDir.empty()) {
      // Append the remaining path to the resolved directory.
      Storage.append(path::get_separator());
      Storage.append(RemainderDir);
    }
    SearchDir = Storage;
  } else {
    SearchDir = path::parent_path(CompletionBuffer);
  }

  size_t FullPrefixLen = CompletionBuffer.size();

  PartialItem = path::filename(CompletionBuffer);

  // path::filename() will return "." when the passed path ends with a
  // directory separator. We have to filter those out, but only when the
  // "." doesn't come from the completion request itself.
  if (PartialItem == "." && path::is_separator(CompletionBuffer.back()))
    PartialItem = llvm::StringRef();

  if (SearchDir.empty()) {
    llvm::sys::fs::current_path(Storage);
    SearchDir = Storage;
  }
  assert(!PartialItem.contains(path::get_separator()));

  // SearchDir now contains the directory to search in, and Prefix contains the
  // text we want to match against items in that directory.

  FileSystem &fs = FileSystem::Instance();
  std::error_code EC;
  llvm::vfs::directory_iterator Iter = fs.DirBegin(SearchDir, EC);
  llvm::vfs::directory_iterator End;
  for (; Iter != End && !EC; Iter.increment(EC)) {
    auto &Entry = *Iter;
    llvm::ErrorOr<llvm::vfs::Status> Status = fs.GetStatus(Entry.path());

    if (!Status)
      continue;

    auto Name = path::filename(Entry.path());

    // Omit ".", ".."
    if (Name == "." || Name == ".." || !Name.startswith(PartialItem))
      continue;

    bool is_dir = Status->isDirectory();

    // If it's a symlink, then we treat it as a directory as long as the target
    // is a directory.
    if (Status->isSymlink()) {
      FileSpec symlink_filespec(Entry.path());
      FileSpec resolved_filespec;
      auto error = fs.ResolveSymbolicLink(symlink_filespec, resolved_filespec);
      if (error.Success())
        is_dir = fs.IsDirectory(symlink_filespec);
    }

    if (only_directories && !is_dir)
      continue;

    // Shrink it back down so that it just has the original prefix the user
    // typed and remove the part of the name which is common to the located
    // item and what the user typed.
    CompletionBuffer.resize(FullPrefixLen);
    Name = Name.drop_front(PartialItem.size());
    CompletionBuffer.append(Name);

    if (is_dir) {
      path::append(CompletionBuffer, path::get_separator());
    }

    matches.AppendString(CompletionBuffer);
  }

  return matches.GetSize();
}
Example #21
0
   ConvolutionFilterCodeDialog::ConvolutionFilterCodeDialog( String mode, const Filter& _filter ) : Dialog(), filter( _filter )
   {
      // ### TextBox
      FilterCode_TextBox.SetScaledMinSize( 700, 300 );
      FilterCode_TextBox.OnCaretPositionUpdated( (TextBox::caret_event_handler)&ConvolutionFilterCodeDialog::__TextBox_CaretPosition, *this );

      if ( mode == "Edit" )
      {
         FilterCode_TextBox.SetReadWrite();
         FilterCode_TextBox.SetText( filter.ToSource() );
      }

      tableRow = 0;
      String s;
      String html( "<html style=\"white-space:pre;text-align:right;\">"
                     "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" );

      StringList cols;
      UpdateTableColors();

      if ( mode == "View" )
      {
         FilterCode_TextBox.SetReadOnly();
         if ( filter.IsSeparable() )
         {
            SeparableFilter fs( filter.Separable() );
            float element;

            // Rows
            for ( int i = 0; i < fs.Size(); ++i )
            {
               // Cols
               for ( int j = 0; j < fs.Size(); ++j )
               {
                  // Calculus of each coefficient of the separable filter
                  element = Round( fs.ColFilter()[i] * fs.RowFilter()[j], 6 );
                  cols.Add( String().Format( "%10.6f", element ) );


               }
               html += TR( cols );
               cols.Clear();
            }
         }
         else
         {
            KernelFilter k( filter.Kernel() );

            for ( int i = 0; i < k.Size(); ++i )
            {
               for ( int j = 0; j < k.Size(); ++j )
               {
                  float element = Round( k.Coefficients()[i][j], 6 );
                  // The elements of the KernelFilter can be accessed directly God thanks and the [] operator.
                  cols.Add( String().Format( "%10.6f", element ) );
               }
               html += TR( cols );
               cols.Clear();
            }
         }
         html += "</table></html>";
         // We got it!! we set the TextBox text by passing the composed String s.
         FilterCode_TextBox.SetText( html );
         UpdateTableColors();
      }

      if ( mode == "View" )
         LineCol_Label.Hide();
      else
         LineCol_Label.Show();

      LineCol_Sizer.SetSpacing( 4 );
      LineCol_Sizer.Add( LineCol_Label );
      LineCol_Sizer.AddStretch();

      // ### Save PushButton
      Save_PushButton.SetText( "Save" );
      Save_PushButton.SetCursor( StdCursor::Checkmark );
      Save_PushButton.OnClick( (Button::click_event_handler)&ConvolutionFilterCodeDialog::__Button_Click, *this );
      if ( mode == "View" )
         Save_PushButton.Hide();
      else
         Save_PushButton.SetDefault();

      if ( mode == "View" )
      {
         Cancel_PushButton.SetText( "Close" );
         Cancel_PushButton.SetCursor( StdCursor::Checkmark );
         Cancel_PushButton.SetDefault();
      }
      else
      {
         Cancel_PushButton.SetText( "Cancel" );
         Cancel_PushButton.SetCursor( StdCursor::Crossmark );
      }
      Cancel_PushButton.OnClick( (Button::click_event_handler)&ConvolutionFilterCodeDialog::__Button_Click, *this );

      DialogButtons_Sizer.SetSpacing( 8 );
      DialogButtons_Sizer.AddStretch();
      DialogButtons_Sizer.Add( Save_PushButton );
      DialogButtons_Sizer.Add( Cancel_PushButton );
      DialogButtons_Sizer.AddStretch();

      Global_Sizer.SetMargin( 4 );
      Global_Sizer.SetSpacing( 4 );
      Global_Sizer.Add( FilterCode_TextBox );
      Global_Sizer.Add( LineCol_Sizer );
      Global_Sizer.Add( DialogButtons_Sizer );

      SetSizer( Global_Sizer );
      EnableUserResizing();
      AdjustToContents();
      BringToFront();
      //SetFixedSize();

      if ( mode == "View" )
         SetWindowTitle( '\"' + filter.Name() + '\"' + " filter elements" );
      else if ( mode == "Edit" )
         SetWindowTitle( '\"' + filter.Name() + '\"' + " edit" );
      else if ( mode == "New" )
         SetWindowTitle( "New filter" );
      else
         throw Error( "Internal error: Invalid dialog operation mode in ConvolutionFilterCodeDialog" );
   }
Example #22
0
int
CommandObject::HandleCompletion
(
    Args &input,
    int &cursor_index,
    int &cursor_char_position,
    int match_start_point,
    int max_return_elements,
    bool &word_complete,
    StringList &matches
)
{
    // Default implmentation of WantsCompletion() is !WantsRawCommandString().
    // Subclasses who want raw command string but desire, for example,
    // argument completion should override WantsCompletion() to return true,
    // instead.
    if (WantsRawCommandString() && !WantsCompletion())
    {
        // FIXME: Abstract telling the completion to insert the completion character.
        matches.Clear();
        return -1;
    }
    else
    {
        // Can we do anything generic with the options?
        Options *cur_options = GetOptions();
        CommandReturnObject result;
        OptionElementVector opt_element_vector;

        if (cur_options != NULL)
        {
            // Re-insert the dummy command name string which will have been
            // stripped off:
            input.Unshift ("dummy-string");
            cursor_index++;


            // I stick an element on the end of the input, because if the last element is
            // option that requires an argument, getopt_long will freak out.

            input.AppendArgument ("<FAKE-VALUE>");

            input.ParseArgsForCompletion (*cur_options, opt_element_vector, cursor_index);

            input.DeleteArgumentAtIndex(input.GetArgumentCount() - 1);

            bool handled_by_options;
            handled_by_options = cur_options->HandleOptionCompletion (input,
                                                                      opt_element_vector,
                                                                      cursor_index,
                                                                      cursor_char_position,
                                                                      match_start_point,
                                                                      max_return_elements,
                                                                      word_complete,
                                                                      matches);
            if (handled_by_options)
                return matches.GetSize();
        }

        // If we got here, the last word is not an option or an option argument.
        return HandleArgumentCompletion (input,
                                         cursor_index,
                                         cursor_char_position,
                                         opt_element_vector,
                                         match_start_point,
                                         max_return_elements,
                                         word_complete,
                                         matches);
    }
}
bool
CommandObjectHelp::DoExecute (Args& command, CommandReturnObject &result)
{
    CommandObject::CommandMap::iterator pos;
    CommandObject *cmd_obj;
    const size_t argc = command.GetArgumentCount ();
    
    // 'help' doesn't take any arguments, other than command names.  If argc is 0, we show the user
    // all commands (aliases and user commands if asked for).  Otherwise every argument must be the name of a command or a sub-command.
    if (argc == 0)
    {
        uint32_t cmd_types = CommandInterpreter::eCommandTypesBuiltin;
        if (m_options.m_show_aliases)
            cmd_types |= CommandInterpreter::eCommandTypesAliases;
        if (m_options.m_show_user_defined)
            cmd_types |= CommandInterpreter::eCommandTypesUserDef;
        if (m_options.m_show_hidden)
            cmd_types |= CommandInterpreter::eCommandTypesHidden;

        result.SetStatus (eReturnStatusSuccessFinishNoResult);
        m_interpreter.GetHelp (result, cmd_types);  // General help
    }
    else
    {
        // Get command object for the first command argument. Only search built-in command dictionary.
        StringList matches;
        cmd_obj = m_interpreter.GetCommandObject (command.GetArgumentAtIndex (0), &matches);
        bool is_alias_command = m_interpreter.AliasExists (command.GetArgumentAtIndex (0));
        std::string alias_name = command.GetArgumentAtIndex(0);
        
        if (cmd_obj != nullptr)
        {
            StringList matches;
            bool all_okay = true;
            CommandObject *sub_cmd_obj = cmd_obj;
            // Loop down through sub_command dictionaries until we find the command object that corresponds
            // to the help command entered.
            std::string sub_command;
            for (size_t i = 1; i < argc && all_okay; ++i)
            {
                sub_command = command.GetArgumentAtIndex(i);
                matches.Clear();
                if (sub_cmd_obj->IsAlias())
                    sub_cmd_obj = ((CommandAlias*)sub_cmd_obj)->GetUnderlyingCommand().get();
                if (! sub_cmd_obj->IsMultiwordObject ())
                {
                    all_okay = false;
                }
                else
                {
                    CommandObject *found_cmd;
                    found_cmd = sub_cmd_obj->GetSubcommandObject(sub_command.c_str(), &matches);
                    if (found_cmd == nullptr)
                        all_okay = false;
                    else if (matches.GetSize() > 1)
                        all_okay = false;
                    else
                        sub_cmd_obj = found_cmd;
                }
            }
            
            if (!all_okay || (sub_cmd_obj == nullptr))
            {
                std::string cmd_string;
                command.GetCommandString (cmd_string);
                if (matches.GetSize() >= 2)
                {
                    StreamString s;
                    s.Printf ("ambiguous command %s", cmd_string.c_str());
                    size_t num_matches = matches.GetSize();
                    for (size_t match_idx = 0; match_idx < num_matches; match_idx++)
                    {
                        s.Printf ("\n\t%s", matches.GetStringAtIndex(match_idx));
                    }
                    s.Printf ("\n");
                    result.AppendError(s.GetData());
                    result.SetStatus (eReturnStatusFailed);
                    return false;
                }
                else if (!sub_cmd_obj)
                {
                    StreamString error_msg_stream;
                    GenerateAdditionalHelpAvenuesMessage(&error_msg_stream,
                                                         cmd_string.c_str(),
                                                         m_interpreter.GetCommandPrefix(),
                                                         sub_command.c_str());
                    result.AppendErrorWithFormat("%s",error_msg_stream.GetData());
                    result.SetStatus (eReturnStatusFailed);
                    return false;
                }
                else
                {
                    GenerateAdditionalHelpAvenuesMessage(&result.GetOutputStream(),
                                                         cmd_string.c_str(),
                                                         m_interpreter.GetCommandPrefix(),
                                                         sub_command.c_str());
                    result.GetOutputStream().Printf("\nThe closest match is '%s'. Help on it follows.\n\n", sub_cmd_obj->GetCommandName());
                }
            }
            
            sub_cmd_obj->GenerateHelpText(result);
            
            if (is_alias_command)
            {
                StreamString sstr;
                m_interpreter.GetAlias(alias_name.c_str())->GetAliasExpansion(sstr);
                result.GetOutputStream().Printf ("\n'%s' is an abbreviation for %s\n", alias_name.c_str(), sstr.GetData());
            }
        }
        else if (matches.GetSize() > 0)
        {
            Stream &output_strm = result.GetOutputStream();
            output_strm.Printf("Help requested with ambiguous command name, possible completions:\n");
            const size_t match_count = matches.GetSize();
            for (size_t i = 0; i < match_count; i++)
            {
                output_strm.Printf("\t%s\n", matches.GetStringAtIndex(i));
            }
        }
        else
        {
            // Maybe the user is asking for help about a command argument rather than a command.
            const CommandArgumentType arg_type = CommandObject::LookupArgumentName (command.GetArgumentAtIndex (0));
            if (arg_type != eArgTypeLastArg)
            {
                Stream &output_strm = result.GetOutputStream ();
                CommandObject::GetArgumentHelp (output_strm, arg_type, m_interpreter);
                result.SetStatus (eReturnStatusSuccessFinishNoResult);
            }
            else
            {
                StreamString error_msg_stream;
                GenerateAdditionalHelpAvenuesMessage(&error_msg_stream, command.GetArgumentAtIndex(0), m_interpreter.GetCommandPrefix());
                result.AppendErrorWithFormat("%s",error_msg_stream.GetData());
                result.SetStatus (eReturnStatusFailed);
            }
        }
    }
    
    return result.Succeeded();
}
void CompletionResult::GetDescriptions(StringList &descriptions) const {
  descriptions.Clear();
  for (const Completion &completion : m_results)
    descriptions.AppendString(completion.m_descripton);
}
void CompletionResult::GetMatches(StringList &matches) const {
  matches.Clear();
  for (const Completion &completion : m_results)
    matches.AppendString(completion.m_completion);
}
Example #26
0
size_t
Platform::GetEnvironment (StringList &environment)
{
    environment.Clear();
    return false;
}
Example #27
0
int
CommandInterpreter::HandleCompletion (const char *current_line,
                                      const char *cursor,
                                      const char *last_char,
                                      int match_start_point,
                                      int max_return_elements,
                                      StringList &matches)
{
    // We parse the argument up to the cursor, so the last argument in parsed_line is
    // the one containing the cursor, and the cursor is after the last character.

    Args parsed_line(current_line, last_char - current_line);
    Args partial_parsed_line(current_line, cursor - current_line);

    int num_args = partial_parsed_line.GetArgumentCount();
    int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
    int cursor_char_position;

    if (cursor_index == -1)
        cursor_char_position = 0;
    else
        cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));

    int num_command_matches;

    matches.Clear();

    // Only max_return_elements == -1 is supported at present:
    assert (max_return_elements == -1);
    bool word_complete;
    num_command_matches = HandleCompletionMatches (parsed_line, 
                                                   cursor_index, 
                                                   cursor_char_position, 
                                                   match_start_point,
                                                   max_return_elements,
                                                   word_complete,
                                                   matches);

    if (num_command_matches <= 0)
            return num_command_matches;

    if (num_args == 0)
    {
        // If we got an empty string, insert nothing.
        matches.InsertStringAtIndex(0, "");
    }
    else
    {
        // Now figure out if there is a common substring, and if so put that in element 0, otherwise
        // put an empty string in element 0.
        std::string command_partial_str;
        if (cursor_index >= 0)
            command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);

        std::string common_prefix;
        matches.LongestCommonPrefix (common_prefix);
        int partial_name_len = command_partial_str.size();

        // If we matched a unique single command, add a space...
        // Only do this if the completer told us this was a complete word, however...
        if (num_command_matches == 1 && word_complete)
        {
            char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
            if (quote_char != '\0')
                common_prefix.push_back(quote_char);

            common_prefix.push_back(' ');
        }
        common_prefix.erase (0, partial_name_len);
        matches.InsertStringAtIndex(0, common_prefix.c_str());
    }
    return num_command_matches;
}
Example #28
0
void RefreshWindowList(HWND hwndCombobox, StringList &classList)
{
    SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0);
    classList.Clear();

    BOOL bCurrentProcessIsWow64 = FALSE;
    IsWow64Process(GetCurrentProcess(), &bCurrentProcessIsWow64);

    HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD);
    do
    {
        if(IsWindowVisible(hwndCurrent))
        {
            RECT clientRect;
            GetClientRect(hwndCurrent, &clientRect);

            HWND hwndParent = GetParent(hwndCurrent);

            DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE);
            DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE);


            if( (exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 && hwndParent == NULL)
            {
                String strWindowName;
                strWindowName.SetLength(GetWindowTextLength(hwndCurrent));
                GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1);

                //-------

                DWORD processID;
                GetWindowThreadProcessId(hwndCurrent, &processID);
                if(processID == GetCurrentProcessId())
                    continue;

                TCHAR fileName[MAX_PATH+1];
                scpy(fileName, TEXT("unknown"));

                HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID);
                if(hProcess)
                {
                    BOOL bTargetProcessIsWow64 = FALSE;
                    IsWow64Process(hProcess, &bTargetProcessIsWow64);

                    DWORD dwSize = MAX_PATH;
                    QueryFullProcessImageName(hProcess, 0, fileName, &dwSize);
                    CloseHandle(hProcess);

                    if(bCurrentProcessIsWow64 != bTargetProcessIsWow64)
                        continue;
                }

                //-------

                String strFileName = fileName;
                strFileName.FindReplace(TEXT("\\"), TEXT("/"));

                String strText;
                strText << TEXT("[") << GetPathFileName(strFileName) << TEXT("]: ") << strWindowName;

                int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strWindowName.Array());
                SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent);

                String strClassName;
                strClassName.SetLength(256);
                GetClassName(hwndCurrent, strClassName.Array(), 255);
                strClassName.SetLength(slen(strClassName));

                classList << strClassName;
            }
        }
    } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT));
}