Example #1
0
//--------------------------------------------------------------------------------------------------
bool smack_HasAccess
(
    const char* subjectLabelPtr,    ///< [IN] Subject label.
    const char* accessModePtr,      ///< [IN] Access mode.
    const char* objectLabelPtr      ///< [IN] Object label.
)
{
    CheckLabel(subjectLabelPtr);
    CheckLabel(objectLabelPtr);

    // Create the SMACK rule.
    char rule[SMACK_RULE_STR_BYTES];
    MakeRuleStr(subjectLabelPtr, accessModePtr, objectLabelPtr, rule, sizeof(rule));

    // Open the SMACK access file.
    int fd;

    do
    {
        fd = open(SMACK_ACCESS_FILE, O_RDWR);
    }
    while ( (fd == -1) && (errno == EINTR) );

    LE_FATAL_IF(fd == -1, "Could not open %s.  %m.\n", SMACK_ACCESS_FILE);

    // Write the rule to the SMACK access file.
    int numBytes = 0;

    do
    {
        numBytes = write(fd, rule, sizeof(rule)-1);
    }
    while ( (numBytes == -1) && (errno == EINTR) );

    LE_FATAL_IF(numBytes < 0, "Could not write SMACK rule '%s'.  %m.", rule);

    // Read the SMACK access file to see if access would be granted.
    char a;
    do
    {
        numBytes = read(fd, &a, 1);
    }
    while ( (numBytes == -1) && (errno == EINTR) );

    LE_FATAL_IF(numBytes <= 0, "Could not read '%s'.  %m.", SMACK_ACCESS_FILE);

    fd_Close(fd);

    return (a == '1');
}
    void AsmJsByteCodeWriter::AsmBrReg2(OpCodeAsmJs op, ByteCodeLabel labelID, RegSlot R1, RegSlot R2)
    {
        CheckOpen();
        CheckLabel(labelID);

        MULTISIZE_LAYOUT_WRITE(AsmBrReg2, op, labelID, R1, R2);
    }
Example #3
0
//--------------------------------------------------------------------------------------------------
void smack_SetRule
(
    const char* subjectLabelPtr,    ///< [IN] Subject label.
    const char* accessModePtr,      ///< [IN] Access mode. See the function description for details.
    const char* objectLabelPtr      ///< [IN] Object label.
)
{
    CheckLabel(subjectLabelPtr);
    CheckLabel(objectLabelPtr);

    // Create the SMACK rule.
    char rule[SMACK_RULE_STR_BYTES];
    MakeRuleStr(subjectLabelPtr, accessModePtr, objectLabelPtr, rule, sizeof(rule));

    // Open the SMACK load file.
    int fd;

    do
    {
        fd = open(SMACK_LOAD_FILE, O_WRONLY);
    }
    while ( (fd == -1) && (errno == EINTR) );

    LE_FATAL_IF(fd == -1, "Could not open %s.  %m.\n", SMACK_LOAD_FILE);

    // Write the rule to the SMACK load file.
    int numBytes = 0;
    size_t ruleLength = strlen(rule);

    do
    {
        numBytes = write(fd, rule, ruleLength);
    }
    while ( (numBytes == -1) && (errno == EINTR) );

    LE_FATAL_IF(numBytes != ruleLength, "Could not write SMACK rule '%s'.  %m.", rule);

    fd_Close(fd);

    LE_DEBUG("Set SMACK rule '%s'.", rule);
}
    void AsmJsByteCodeWriter::AsmBr(ByteCodeLabel labelID, OpCodeAsmJs op)
    {
        CheckOpen();
        CheckLabel(labelID);

        size_t const offsetOfRelativeJumpOffsetFromEnd = sizeof(OpLayoutAsmBr) - offsetof(OpLayoutAsmBr, RelativeJumpOffset);
        OpLayoutAsmBr data;
        data.RelativeJumpOffset = offsetOfRelativeJumpOffsetFromEnd;

        m_byteCodeData.Encode(op, &data, sizeof(data), this);
        AddJumpOffset(op, labelID, offsetOfRelativeJumpOffsetFromEnd);
    }
Example #5
0
static void CheckStateLabels(PClassActor *obj, ENamedName *test, int useflag,  const char *descript)
{
	FStateLabels *labels = obj->StateList;

	for (; *test != NAME_None; test++)
	{
		auto label = labels->FindLabel(*test);
		if (label != nullptr)
		{
			CheckLabel(obj, label, useflag, *test, descript);
		}
	}
}
Example #6
0
//--------------------------------------------------------------------------------------------------
le_result_t smack_SetLabel
(
    const char* objPathPtr,         ///< [IN] Path to the object.
    const char* labelPtr            ///< [IN] Label to set the object to.
)
{
    CheckLabel(labelPtr);

    if (setxattr(objPathPtr, "security.SMACK64", labelPtr, strlen(labelPtr), 0) == -1)
    {
        LE_ERROR("Could not set SMACK label for '%s'.  %m.", objPathPtr);
        return LE_FAULT;
    }

    LE_DEBUG("Set SMACK label to '%s' for %s.", labelPtr, objPathPtr);

    return LE_OK;
}
    void AsmJsByteCodeWriter::AddJumpOffset(Js::OpCodeAsmJs op, ByteCodeLabel labelId, uint fieldByteOffset)
    {
        AssertMsg(fieldByteOffset < 100, "Ensure valid field offset");
        CheckOpen();
        CheckLabel(labelId);

        uint jumpByteOffset = m_byteCodeData.GetCurrentOffset() - fieldByteOffset;

        //
        // Branch targets are created in two passes:
        // - In the instruction stream, write "labelID" into "OpLayoutBrC.Offset". Record this
        //   location in "m_jumpOffsets" to be patched later.
        // - When the bytecode is closed, update all "OpLayoutBrC.Offset"'s with their actual
        //   destinations.
        //

        JumpInfo jumpInfo = { labelId, jumpByteOffset };
        m_jumpOffsets->Add(jumpInfo);
    }
Example #8
0
static void CheckLabel(PClassActor *obj, FStateLabel *slb, int useflag, FName statename, const char *descript)
{
	auto state = slb->State;
	if (state != nullptr)
	{
		if (!(state->UseFlags & useflag))
		{
			auto owner = FState::StaticFindStateOwner(state);
			GetStateSource(state).Message(MSG_ERROR, TEXTCOLOR_RED "%s references state %s.%d as %s state, but this state is not flagged for use as %s.\n",
				obj->TypeName.GetChars(), owner->TypeName.GetChars(), int(state - owner->OwnedStates), statename.GetChars(), descript);
		}
	}
	if (slb->Children != nullptr)
	{
		for (int i = 0; i < slb->Children->NumLabels; i++)
		{
			auto state = slb->Children->Labels[i].State;
			CheckLabel(obj, &slb->Children->Labels[i], useflag, statename, descript);
		}
	}
}
Example #9
0
//--------------------------------------------------------------------------------------------------
void smack_SetMyLabel
(
    const char* labelPtr            ///< [IN] Label to set the calling process to.
)
{
    CheckLabel(labelPtr);

    // Open the calling process's smack file.
    int fd;

    do
    {
        fd = open(PROC_SMACK_FILE, O_WRONLY);
    }
    while ( (fd == -1) && (errno == EINTR) );

    LE_FATAL_IF(fd == -1, "Could not open %s.  %m.\n", PROC_SMACK_FILE);

    // Write the label to the file.
    size_t labelSize = strlen(labelPtr);

    int result;

    do
    {
        result = write(fd, labelPtr, labelSize);
    }
    while ( (result == -1) && (errno == EINTR) );

    LE_FATAL_IF(result != labelSize,
                "Could not write to %s.  %m.\n", PROC_SMACK_FILE);

    fd_Close(fd);

    LE_DEBUG("Setting process' SMACK label to '%s'.", labelPtr);
}
Example #10
0
int
main(int argc, char **argv)
{
  char *name;
  const char *lastlabel;
  int arg, f, holdfd[3], label;
  struct bundle *bundle;
  struct prompt *prompt;
  struct switches sw;

  probe_Init();

  /*
   * We open 3 descriptors to ensure that STDIN_FILENO, STDOUT_FILENO and
   * STDERR_FILENO are always open.  These are closed before DoLoop(),
   * but *after* we've avoided the possibility of erroneously closing
   * an important descriptor with close(STD{IN,OUT,ERR}_FILENO).
   */
  if ((holdfd[0] = open(_PATH_DEVNULL, O_RDWR)) == -1) {
    fprintf(stderr, "Cannot open %s !\n", _PATH_DEVNULL);
    return 2;
  }
  for (f = 1; f < sizeof holdfd / sizeof *holdfd; f++)
    holdfd[f] = dup(holdfd[0]);

  name = strrchr(argv[0], '/');
  log_Open(name ? name + 1 : argv[0]);

#ifndef NONAT
  PacketAliasInit();
#endif
  label = ProcessArgs(argc, argv, &sw);

  /*
   * A FreeBSD & OpenBSD hack to dodge a bug in the tty driver that drops
   * output occasionally.... I must find the real reason some time.  To
   * display the dodgy behaviour, comment out this bit, make yourself a large
   * routing table and then run ppp in interactive mode.  The `show route'
   * command will drop chunks of data !!!
   */
  if (sw.mode == PHYS_INTERACTIVE) {
    close(STDIN_FILENO);
    if (open(_PATH_TTY, O_RDONLY) != STDIN_FILENO) {
      fprintf(stderr, "Cannot open %s for input !\n", _PATH_TTY);
      return 2;
    }
  }

  /* Allow output for the moment (except in direct mode) */
  if (sw.mode == PHYS_DIRECT)
    prompt = NULL;
  else
    SignalPrompt = prompt = prompt_Create(NULL, NULL, PROMPT_STD);

  ID0init();
  if (ID0realuid() != 0) {
    char conf[200], *ptr;

    snprintf(conf, sizeof conf, "%s/%s", PPP_CONFDIR, CONFFILE);
    do {
      struct stat sb;

      if (stat(conf, &sb) == 0 && sb.st_mode & S_IWOTH) {
        log_Printf(LogALERT, "ppp: Access violation: Please protect %s\n",
                   conf);
        return -1;
      }
      ptr = conf + strlen(conf)-2;
      while (ptr > conf && *ptr != '/')
        *ptr-- = '\0';
    } while (ptr >= conf);
  }

  if (label < argc)
    for (arg = label; arg < argc; arg++)
      CheckLabel(argv[arg], prompt, sw.mode);
  else
    CheckLabel("default", prompt, sw.mode);

  if (!sw.quiet)
    prompt_Printf(prompt, "Working in %s mode\n", mode2Nam(sw.mode));

  if ((bundle = bundle_Create(TUN_PREFIX, sw.mode, sw.unit)) == NULL)
    return EX_START;

  /* NOTE:  We may now have changed argv[1] via a ``set proctitle'' */

  if (prompt) {
    prompt->bundle = bundle;	/* couldn't do it earlier */
    if (!sw.quiet)
      prompt_Printf(prompt, "Using interface: %s\n", bundle->iface->name);
  }
  SignalBundle = bundle;
  bundle->NatEnabled = sw.nat;
  if (sw.nat)
    opt_enable(bundle, OPT_IFACEALIAS);

  if (system_Select(bundle, "default", CONFFILE, prompt, NULL) < 0)
    prompt_Printf(prompt, "Warning: No default entry found in config file.\n");

  sig_signal(SIGHUP, CloseSession);
  sig_signal(SIGTERM, CloseSession);
  sig_signal(SIGINT, CloseConnection);
  sig_signal(SIGQUIT, CloseSession);
  sig_signal(SIGALRM, SIG_IGN);
  signal(SIGPIPE, SIG_IGN);

  if (sw.mode == PHYS_INTERACTIVE)
    sig_signal(SIGTSTP, TerminalStop);

  sig_signal(SIGUSR1, RestartServer);
  sig_signal(SIGUSR2, BringDownServer);

  lastlabel = argv[argc - 1];
  for (arg = label; arg < argc; arg++) {
    /* In case we use LABEL or ``set enddisc label'' */
    bundle_SetLabel(bundle, lastlabel);
    system_Select(bundle, argv[arg], CONFFILE, prompt, NULL);
  }

  if (label < argc)
    /* In case the last label did a ``load'' */
    bundle_SetLabel(bundle, lastlabel);

  if (sw.mode == PHYS_AUTO &&
      ncprange_family(&bundle->ncp.ipcp.cfg.peer_range) == AF_UNSPEC) {
    prompt_Printf(prompt, "You must ``set ifaddr'' with a peer address "
                  "in auto mode.\n");
    AbortProgram(EX_START);
  }

  if (sw.mode != PHYS_INTERACTIVE) {
    if (sw.mode != PHYS_DIRECT) {
      if (!sw.fg) {
        int bgpipe[2];
        pid_t bgpid;

        if (sw.mode == PHYS_BACKGROUND && pipe(bgpipe)) {
          log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
	  AbortProgram(EX_SOCK);
        }

        bgpid = fork();
        if (bgpid == -1) {
	  log_Printf(LogERROR, "fork: %s\n", strerror(errno));
	  AbortProgram(EX_SOCK);
        }

        if (bgpid) {
	  char c = EX_NORMAL;
          int ret;

	  if (sw.mode == PHYS_BACKGROUND) {
	    close(bgpipe[1]);
	    BGPid = bgpid;
            /* If we get a signal, kill the child */
            signal(SIGHUP, KillChild);
            signal(SIGTERM, KillChild);
            signal(SIGINT, KillChild);
            signal(SIGQUIT, KillChild);

	    /* Wait for our child to close its pipe before we exit */
            while ((ret = read(bgpipe[0], &c, 1)) == 1) {
              switch (c) {
                case EX_NORMAL:
                  if (!sw.quiet) {
	            prompt_Printf(prompt, "PPP enabled\n");
	            log_Printf(LogPHASE, "Parent: PPP enabled\n");
                  }
	          break;
                case EX_REDIAL:
                  if (!sw.quiet)
	            prompt_Printf(prompt, "Attempting redial\n");
                  continue;
                case EX_RECONNECT:
                  if (!sw.quiet)
	            prompt_Printf(prompt, "Attempting reconnect\n");
                  continue;
	        default:
	          prompt_Printf(prompt, "Child failed (%s)\n",
                                ex_desc((int)c));
	          log_Printf(LogPHASE, "Parent: Child failed (%s)\n",
		             ex_desc((int) c));
	      }
	      break;
            }
            if (ret != 1) {
	      prompt_Printf(prompt, "Child exit, no status.\n");
	      log_Printf(LogPHASE, "Parent: Child exit, no status.\n");
	    }
	    close(bgpipe[0]);
	  }
	  return c;
        } else if (sw.mode == PHYS_BACKGROUND) {
	  close(bgpipe[0]);
          bundle->notify.fd = bgpipe[1];
        }

        bundle_ChangedPID(bundle);
        bundle_LockTun(bundle);	/* we have a new pid */
      }

      /* -auto, -dedicated, -ddial, -foreground & -background */
      prompt_Destroy(prompt, 0);
      close(STDOUT_FILENO);
      close(STDERR_FILENO);
      close(STDIN_FILENO);
      if (!sw.fg)
        setsid();
    } else {
      /* -direct - STDIN_FILENO gets used by physical_Open */
      prompt_TtyInit(NULL);
      close(STDOUT_FILENO);
      close(STDERR_FILENO);
    }
  } else {
    /* -interactive */
    close(STDERR_FILENO);
    prompt_TtyInit(prompt);
    prompt_TtyCommandMode(prompt);
    prompt_Required(prompt);
  }

  /* We can get rid of these now */
  for (f = 0; f < sizeof holdfd / sizeof *holdfd; f++)
    close(holdfd[f]);

  log_Printf(LogPHASE, "PPP Started (%s mode).\n", mode2Nam(sw.mode));
  DoLoop(bundle);
  AbortProgram(EX_NORMAL);

  return EX_NORMAL;
}
Example #11
0
void CAliasDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);

  if(!pDX->m_bSaveAndValidate)
    {
    if (m_current_alias && m_current_alias->bIncluded)
      m_strIncluded = "(included)";
    else 
      m_strIncluded.Empty ();
    }

	//{{AFX_DATA_MAP(CAliasDlg)
	DDX_Control(pDX, IDC_SEND_TO, m_ctlSendTo);
	DDX_Control(pDX, IDC_VARIABLE, m_ctlVariable);
	DDX_Control(pDX, IDC_REGEXP, m_ctlRegexp);
	DDX_Control(pDX, IDC_ALIAS_CONTENTS, m_ctlAliasContents);
	DDX_Control(pDX, IDC_ALIAS_NAME, m_ctlAliasName);
	DDX_Text(pDX, IDC_ALIAS_CONTENTS, m_contents);
	DDX_Text(pDX, IDC_ALIAS_NAME, m_name);
	DDX_Text(pDX, IDC_ALIAS_LABEL, m_strLabel);
	DDX_Check(pDX, IDC_ENABLED, m_bEnabled);
	DDX_Text(pDX, IDC_SCRIPT_NAME, m_strProcedure);
	DDX_Check(pDX, IDC_IGNORE_CASE, m_bIgnoreCase);
	DDX_Check(pDX, IDC_EXPAND_VARIABLES, m_bExpandVariables);
	DDX_Check(pDX, IDC_OMIT_FROM_LOG, m_bOmitFromLogFile);
	DDX_Check(pDX, IDC_REGEXP, m_bRegexp);
	DDX_Check(pDX, IDC_OMIT_FROM_OUTPUT, m_bOmitFromOutput);
	DDX_Check(pDX, IDC_ALIAS_MENU, m_bMenu);
	DDX_Check(pDX, IDC_TEMPORARY_ALIAS, m_bTemporary);
	DDX_Text(pDX, IDC_GROUP, m_strGroup);
	DDX_Text(pDX, IDC_VARIABLE, m_strVariable);
	DDX_CBIndex(pDX, IDC_SEND_TO, m_iSendTo);
	DDX_Check(pDX, IDC_KEEP_EVALUATING, m_bKeepEvaluating);
	DDX_Text(pDX, IDC_SEQUENCE, m_iSequence);
	DDV_MinMaxInt(pDX, m_iSequence, 0, 10000);
	DDX_Check(pDX, IDC_ECHO_ALIAS, m_bEchoAlias);
	DDX_Check(pDX, IDC_OMIT_FROM_COMMAND_HISTORY, m_bOmitFromCommandHistory);
	DDX_Text(pDX, IDC_INCLUDED, m_strIncluded);
	DDX_Text(pDX, IDC_REGEXP_ERROR, m_strRegexpError);
	DDX_Check(pDX, IDC_ONE_SHOT, m_bOneShot);
	//}}AFX_DATA_MAP

 if(pDX->m_bSaveAndValidate)
   {
    POSITION pos;
    CAlias * alias_item;

    m_strLabel.TrimLeft ();
    m_strLabel.TrimRight ();

    m_strProcedure.TrimLeft ();
    m_strProcedure.TrimRight ();

    m_strGroup.TrimLeft ();
    m_strGroup.TrimRight ();

    m_strVariable.TrimLeft ();
    m_strVariable.TrimRight ();

    if (m_name.IsEmpty ())
        {
        ::TMessageBox("The alias cannot be blank.");
        DDX_Text(pDX, IDC_ALIAS_NAME, m_name);
        pDX->Fail();
        }     // end of alias being blank

    // check for foolishly using ** in a non-regular expression
    if (m_name.Find ("**") != -1 && !m_bRegexp)
      {
      CCreditsDlg dlg;

      dlg.m_iResourceID = IDR_MULTIPLE_ASTERISKS;
      dlg.m_strTitle = "Warning";

      dlg.DoModal ();	

      DDX_Text(pDX, IDC_ALIAS_NAME, m_name);
      pDX->Fail();

      }

    int iInvalidPos = m_name.FindOneOf ("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"); 

    if (iInvalidPos != -1)
        {
        char c = m_name [iInvalidPos];

        ::UMessageBox(TFormat (
           "The alias 'match' text contains an invalid non-printable character (hex %02X) at position %i.", c, iInvalidPos + 1), MB_ICONSTOP);
        DDX_Text(pDX, IDC_ALIAS_NAME, m_name);
        pDX->Fail();
        }     // end of alias match having weird characters in it


    // we allow carriage-return, linefeed, tab here
    iInvalidPos = m_contents.FindOneOf ("\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0E\x0F"); 

    if (iInvalidPos != -1)
        {
        char c = m_contents [iInvalidPos];

        ::UMessageBox(TFormat (
           "The alias 'send' text contains an invalid non-printable character (hex %02X) at position %i.", c, iInvalidPos + 1), MB_ICONSTOP);
        DDX_Text(pDX, IDC_ALIAS_CONTENTS, m_contents);
        pDX->Fail();
        }     // end of alias send having weird characters in it


    // compile regular expression to check it
    if (m_bRegexp)
      {
      if (!CheckRegularExpression (m_name, (m_bIgnoreCase ?  0 : PCRE_CASELESS) 
          | (m_pDoc->m_bUTF_8 ? PCRE_UTF8 : 0)
#if ALIASES_USE_UTF8
                                  | (m_pDoc->m_bUTF_8 ? PCRE_UTF8 : 0)
#endif // ALIASES_USE_UTF8
          
          ))
        {   // failed check
        DDX_Text(pDX, IDC_ALIAS_NAME, m_name);
        pDX->Fail();
        }
      } // end of checking regular expression

    CString strAliasName;

    for (pos = m_pAliasMap->GetStartPosition (); pos; )
      {
      m_pAliasMap->GetNextAssoc (pos, strAliasName, alias_item);

// don't compare against itself

      if (alias_item == m_current_alias)
        continue;

      /*
      
      bool bDuplicate = false;

      // if either one is case-insensitive, compare insensitive
      if ((alias_item->bIgnoreCase || m_bIgnoreCase) &&
           alias_item->name.CompareNoCase (m_name) == 0)
            bDuplicate = true; 
      // if both are case-sensitive, compare exactly
      else if (alias_item->name == m_name)
            bDuplicate = true; 

      // we won't consider it a match if they send to different places
      if (alias_item->iSendTo != m_iSendTo)
         bDuplicate = false;

      if (bDuplicate)
        {
        ::TMessageBox("This alias is already in the list of aliases.");
        DDX_Text(pDX, IDC_ALIAS_NAME, m_name);
        pDX->Fail();
        }

         */

// now check the label for duplicates

      if (!m_strLabel.IsEmpty ())    // we can have duplicate blank names
        if (m_strLabel.CompareNoCase (alias_item->strLabel) == 0)
          {
          CString strMsg;
          strMsg = TFormat ("The alias label \"%s\" is already in the list of aliases.",
                          (LPCTSTR) m_strLabel);
          ::UMessageBox(strMsg);
          DDX_Text(pDX, IDC_ALIAS_LABEL, m_strLabel);
          pDX->Fail();
          }

      }   // end of checking each alias

    if (!m_strLabel.IsEmpty ())    // we can have blank labels
      {

// check label is valid

      if (CheckLabel (m_strLabel))
        {
        ::TMessageBox("The label must start with a letter and consist of letters"
                        ", numbers or the underscore character.");
        DDX_Text(pDX, IDC_ALIAS_LABEL, m_strLabel);
        pDX->Fail();
        }

      }   // end of having non-blank label

    if (m_strVariable.IsEmpty ())    // we can have blank variables
      {
      if (m_iSendTo == eSendToVariable)
        {
        ::TMessageBox("When sending to a variable you must specify a variable name. ",
                        MB_ICONSTOP);
        DDX_Text(pDX, IDC_VARIABLE, m_strVariable);
        pDX->Fail();
        }
      }
    else
      {

// check variable name is valid

      if (CheckLabel (m_strVariable))
        {
        ::TMessageBox("The variable name must start with a letter and consist of letters"
                        ", numbers or the underscore character.");
        DDX_Text(pDX, IDC_VARIABLE, m_strVariable);
        pDX->Fail();
        }

      }   // end of having non-blank variable

    // check for speed walking OK, unless they are substituting

    if (!m_bExpandVariables || m_contents.Find ('@') == -1)
      if (m_iSendTo == eSendToSpeedwalk && m_contents.Find ('%') == -1)
        {

        CString strResult = m_pDoc->DoEvaluateSpeedwalk (m_contents);

        if (!strResult.IsEmpty ())
          {
          if (strResult [0] == '*')    // error in speedwalk string?
            {
            ::UMessageBox (strResult.Mid (1));
            DDX_Text(pDX, IDC_ALIAS_CONTENTS, m_contents);
            pDX->Fail();
            }   // end of error message
          } // end of non-empty speedwalk          
        }   // end of speed walking wanted


    if(m_contents.IsEmpty () && m_strProcedure.IsEmpty ())
        {
        ::TMessageBox("The alias contents cannot be blank unless you specify a script subroutine.");
        DDX_Text(pDX, IDC_ALIAS_CONTENTS, m_contents);
        pDX->Fail();
        }     // end of contents being blank

    
    if (!m_strProcedure.IsEmpty ())    // blank procedure is OK
      {

// check procedure is valid

      if (CheckLabel (m_strProcedure, true))
        {
        ::TMessageBox("The script subroutine name must start with a letter and consist of letters"
                        ", numbers or the underscore character.");
        DDX_Text(pDX, IDC_SCRIPT_NAME, m_strProcedure);
        pDX->Fail();
        }

      }   // end of having non-blank procedure

   } // end of saving and validating
  else
    if (App.m_bFixedFontForEditing)
      {     
      FixFont (m_font, m_ctlAliasName, App.m_strFixedPitchFont, App.m_iFixedPitchFontSize, FW_NORMAL, DEFAULT_CHARSET);
      FixFont (m_font2, m_ctlAliasContents, App.m_strFixedPitchFont, App.m_iFixedPitchFontSize, FW_NORMAL, DEFAULT_CHARSET);
      }

}
Example #12
0
void ADMMCut::MakeLayers()
{
	// Initial Cutting Edge Setting
	InitState();

	debug_ = false;
	int cut_count = 0;
	vector<double> cut_energy;
	vector<double> res_energy;
	do
	{
		/* Recreate dual graph at the beginning of each cut */
		SetStartingPoints(cut_count);
		CreateA();

		ptr_stiff_->CalculateD(D_, x_, 0, 0, cut_count);

		///* for rendering */
		//if (cut_count == 0)
		//{
		//	WriteWeight();
		//	WriteStiffness("offset1.txt", "rotation1.txt");
		//	getchar();
		//}
		//if (cut_count == 4)
		//{
		//	WriteStiffness("offset2.txt", "rotation2.txt");
		//	getchar();
		//}
		//if (cut_count == 6)
		//{
		//	WriteStiffness("offset3.txt", "rotation3.txt");
		//	getchar();
		//}

		/* set x for intial cut setting */
		SetBoundary();

		/*
		* energy specify:
		* cut		 energy : | A * x |
		* defomation energy : norm(K D - F)
		*/
		ptr_stiff_->CreateGlobalK(x_);
		ptr_stiff_->CreateF(x_);
		SpMat K_init = *(ptr_stiff_->WeightedK());
		VX	  F_init = *(ptr_stiff_->WeightedF());


		double icut_energy = 0;
		VX V_Cut = A_ * x_;
		for (int i = 0; i < Md_; i++)
		{
			icut_energy += abs(V_Cut[i]);
		}
		double ideform_energy = (K_init * D_ - F_init).norm();

		cout << "****************************************" << endl;
		cout << "ADMMCut Round : " << cut_count << endl;
		cout << "Initial cut energy before entering ADMM: " << icut_energy << endl;
		cout << "Initial Lagrangian energy before entering ADMM: " << ideform_energy << endl;
		cout << "---------------------------------" << endl;

		int rew_count = 0;
		VX x_prev;
		VX D_prev;

		/* Output energy list for reweighting process in a single
		graph cut problem, energy.size() = number of reweighting
		process performed.
		cut energy = |A_ * x_| = sum_{e_ij} w_ij * |x_i - x_j|
		res energy = (K(x)D - F(x)).norm()
		*/

		cut_energy.clear();
		res_energy.clear();

		cut_energy.push_back(icut_energy);
		res_energy.push_back(ideform_energy);

		do
		{
			/* Reweighting loop for cut */

			int ADMM_count = 0;
			x_prev = x_;
			CreateC(cut_count, rew_count);

			do
			{
				cout << "ADMMCut Round: " << cut_count << ", reweight iteration:" << rew_count
					<< ", ADMM " << ADMM_count << " iteration." << endl;

				/*-------------------ADMM loop-------------------*/
				CalculateX();

				D_prev = D_;
				CalculateD();

				UpdateLambda();

				/*-------------------Residual Calculation-------------------*/
				SpMat Q_prev;
				SpMat Q_new;
				CalculateQ(D_prev, Q_prev);
				CalculateQ(D_, Q_new);

				/* Update K reweighted by new x */
				ptr_stiff_->CreateGlobalK(x_);
				ptr_stiff_->CreateF(x_);
				SpMat K_new = *(ptr_stiff_->WeightedK());
				VX    F_new = *(ptr_stiff_->WeightedF());

				dual_res_ = penalty_ * (D_prev - D_).transpose() * K_new.transpose() * Q_prev
					+ lambda_.transpose() * (Q_prev - Q_new);
				primal_res_ = K_new * D_ - F_new;

				/*-------------------Screenplay-------------------*/
				double new_cut_energy = x_.dot(H1_ * x_);

				cout << "new quadratic func value record: " << new_cut_energy << endl;
				cout << "dual_residual : " << dual_res_.norm() << endl;
				cout << "primal_residual(KD-F) : " << primal_res_.norm() << endl;

				cout << "---------------------" << endl;
				ADMM_count++;
			} while (!TerminationCriteria(ADMM_count));

			/* One reweighting process ended! */
			/* Output energy and residual */

			double energy = 0;
			VX V_Cut = A_ * x_;
			for (int i = 0; i < Md_; i++)
			{
				energy += ptr_dualgraph_->Weight(i) * abs(V_Cut[i]);
			}

			/*-------------------Screenplay-------------------*/
			double res_tmp = primal_res_.norm();
			cout << "Cut " << cut_count << " Reweight " << rew_count << " completed." << endl;
			cout << "Cut Energy :" << energy << endl;
			cout << "Res Energy :" << res_tmp << endl;
			cout << "<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-" << endl;

			cut_energy.push_back(energy);
			res_energy.push_back(res_tmp);

			/* write x distribution to a file */
			string str_x = "Cut_" + to_string(cut_count) + "_Rew_" + to_string(rew_count) + "_x";
			Statistics tmp_x(str_x, x_);
			tmp_x.GenerateVectorFile();

			rew_count++;
		} while (!UpdateR(x_prev, rew_count));

		/* Output reweighting energy history for last cut process */
		string str_eC = "Cut_" + to_string(cut_count) + "_Cut_Energy";
		Statistics s_eC(str_eC, cut_energy);
		s_eC.GenerateStdVecFile();

		string str_eR = "Cut_" + to_string(cut_count) + "_Res_Energy";
		Statistics s_eR(str_eR, res_energy);
		s_eR.GenerateStdVecFile();

		/* Update New Cut information to Rendering (layer_label_) */

		UpdateCut();

		fprintf(stdout, "ADMMCut No.%d process is Finished!\n", cut_count);
		cut_count++;

	} while (!CheckLabel(cut_count));

	fprintf(stdout, "All done!\n");
}
Example #13
0
void CTimerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);

  if(!pDX->m_bSaveAndValidate)
    {
    if (m_current_timer && m_current_timer->bIncluded)
      m_strIncluded = "(included)";
    else 
      m_strIncluded.Empty ();
    }

	//{{AFX_DATA_MAP(CTimerDlg)
	DDX_Control(pDX, IDC_SEND_TO, m_ctlSendTo);
	DDX_Control(pDX, IDC_SCRIPT_NAME, m_ctlProcedure);
	DDX_Control(pDX, IDC_TIMER_CONTENTS, m_ctlContents);
	DDX_Control(pDX, IDC_BUTTON_AT, m_ctlButtonAt);
	DDX_Check(pDX, IDC_ENABLED, m_bEnabled);
	DDX_Text(pDX, IDC_TIMER_LABEL, m_strLabel);
	DDX_Text(pDX, IDC_AT_HOUR, m_iAtHour);
	DDV_MinMaxInt(pDX, m_iAtHour, 0, 23);
	DDX_Text(pDX, IDC_AT_MINUTE, m_iAtMinute);
	DDV_MinMaxInt(pDX, m_iAtMinute, 0, 59);
	DDX_Text(pDX, IDC_INTERVAL_HOUR, m_iEveryHour);
	DDV_MinMaxInt(pDX, m_iEveryHour, 0, 23);
	DDX_Text(pDX, IDC_INTERVAL_MINUTE, m_iEveryMinute);
	DDV_MinMaxInt(pDX, m_iEveryMinute, 0, 59);
	DDX_Text(pDX, IDC_OFFSET_HOUR, m_iOffsetHour);
	DDV_MinMaxInt(pDX, m_iOffsetHour, 0, 23);
	DDX_Text(pDX, IDC_OFFSET_MINUTE, m_iOffsetMinute);
	DDV_MinMaxInt(pDX, m_iOffsetMinute, 0, 59);
	DDX_MinMaxString(pDX, IDC_TIMER_CONTENTS, m_strContents);
	DDV_MinMaxString(pDX, m_strContents, 0, 32000);
	DDX_Radio(pDX, IDC_BUTTON_EVERY, m_iType);
	DDX_Text(pDX, IDC_SCRIPT_NAME, m_strProcedure);
	DDX_Check(pDX, IDC_ONE_SHOT_TIMER, m_bOneShot);
	DDX_Check(pDX, IDC_TEMPORARY, m_bTemporary);
	DDX_Check(pDX, IDC_ACTIVE_WHEN_CLOSED, m_bActiveWhenClosed);
	DDX_Text(pDX, IDC_GROUP, m_strGroup);
	DDX_CBIndex(pDX, IDC_SEND_TO, m_iSendTo);
	DDX_Text(pDX, IDC_VARIABLE, m_strVariable);
	DDX_Text(pDX, IDC_INCLUDED, m_strIncluded);
	DDX_Check(pDX, IDC_OMIT_FROM_OUTPUT, m_bOmitFromOutput);
	DDX_Check(pDX, IDC_OMIT_FROM_LOG, m_bOmitFromLog);
	DDX_Text(pDX, IDC_AT_SECOND, m_fAtSecond);
	DDV_MinMaxDouble(pDX, m_fAtSecond, 0., 59.99999);
	DDX_Text(pDX, IDC_INTERVAL_SECOND, m_fEverySecond);
	DDV_MinMaxDouble(pDX, m_fEverySecond, 0., 59.99999);
	DDX_Text(pDX, IDC_OFFSET_SECOND, m_fOffsetSecond);
	DDV_MinMaxDouble(pDX, m_fOffsetSecond, 0., 59.99999);
	//}}AFX_DATA_MAP

  if(pDX->m_bSaveAndValidate)
    {

    
    m_strLabel.TrimLeft ();
    m_strLabel.TrimRight ();

    m_strProcedure.TrimLeft ();
    m_strProcedure.TrimRight ();

    m_strGroup.TrimLeft ();
    m_strGroup.TrimRight ();

    if (m_iType == CTimer::eInterval)
      {
      CmcDateTimeSpan ts1 (0, m_iEveryHour, m_iEveryMinute, m_fEverySecond);
      CmcDateTimeSpan ts2 (0, m_iOffsetHour, m_iOffsetMinute, m_fOffsetSecond);

      if (ts1 <= CmcDateTimeSpan (0, 0, 0, 0))
          {
          ::TMessageBox("The timer interval must be greater than zero.");
          DDX_Text(pDX, IDC_INTERVAL_HOUR, m_iEveryHour);
          pDX->Fail();
          }     // end of interval <= 0

      if(ts2 >= ts1)
          {
          ::TMessageBox("The timer offset must be less than the timer period.");
          DDX_Text(pDX, IDC_OFFSET_HOUR, m_iOffsetHour);
          pDX->Fail();
          }     // end of offset >= period
        }   // end of doing a periodical timer


    CString strTimerName;
    CTimer * timer_item;
    POSITION pos;

    for (pos = m_pTimerMap->GetStartPosition (); pos; )
      {
      m_pTimerMap->GetNextAssoc (pos, strTimerName, timer_item);

// don't compare against itself

      if (timer_item == m_current_timer)
        continue;

// now check the label for duplicates

      if (!m_strLabel.IsEmpty ())    // we can have duplicate blank names
        if (m_strLabel.CompareNoCase (timer_item->strLabel) == 0)
          {
          CString strMsg;
          strMsg = TFormat ("The timer label \"%s\" is already in the list of timers.",
                          (LPCTSTR) m_strLabel);
          ::UMessageBox(strMsg);
          DDX_Text(pDX, IDC_TIMER_LABEL, m_strLabel);
          pDX->Fail();
          }

      }   // end of checking each Timer

    if (!m_strLabel.IsEmpty ())    // we can have blank labels
      {

// check label is valid

      if (CheckLabel (m_strLabel))
        {
        ::TMessageBox ("The label must start with a letter and consist of letters"
                        ", numbers or the underscore character.");
        DDX_Text(pDX, IDC_TIMER_LABEL, m_strLabel);
        pDX->Fail();
        }

      }   // end of having non-blank label


    if (m_strVariable.IsEmpty ())    // we can have blank variables
      {
      if (m_iSendTo == eSendToVariable)
        {
        ::TMessageBox("When sending to a variable you must specify a variable name. ",
                        MB_ICONSTOP);
        DDX_Text(pDX, IDC_VARIABLE, m_strVariable);
        pDX->Fail();
        }
      }
    else
      {

// check variable name is valid

      if (CheckLabel (m_strVariable))
        {
        ::TMessageBox("The variable name must start with a letter and consist of letters"
                        ", numbers or the underscore character.");
        DDX_Text(pDX, IDC_VARIABLE, m_strVariable);
        pDX->Fail();
        }

      }   // end of having non-blank variable


    // check for speed walking OK, unless they are substituting

    if (m_iSendTo == eSendToSpeedwalk)
      {

      CString strResult = m_pDoc->DoEvaluateSpeedwalk (m_strContents);

      if (!strResult.IsEmpty ())
        {
        if (strResult [0] == '*')    // error in speedwalk string?
          {
          ::UMessageBox (strResult.Mid (1));  // already translated, I think
          DDX_Text(pDX, IDC_TIMER_CONTENTS, m_strContents);
          pDX->Fail();
          }   // end of error message
        } // end of non-empty speedwalk          
      }   // end of speed walking wanted

    if(m_strContents.IsEmpty () && m_strProcedure.IsEmpty ())
        {
        ::TMessageBox("The timer contents cannot be blank unless you specify a script subroutine.");
        DDX_Text(pDX, IDC_TIMER_CONTENTS, m_strContents);
        pDX->Fail();
        }     // end of contents being blank


    if (!m_strProcedure.IsEmpty ())    // blank procedure is OK
      {

// check procedure is valid

      if (CheckLabel (m_strProcedure, true))
        {
        ::TMessageBox("The script subroutine name must start with a letter and consist of letters"
                        ", numbers or the underscore character.");
        DDX_Text(pDX, IDC_SCRIPT_NAME, m_strProcedure);
        pDX->Fail();
        }

      }   // end of having non-blank procedure

    }   // end of saving and validating

}
Example #14
0
static int IndentNormal(EBuffer *B, int Line, int /*StateLen*/, hsState * /*StateMap*/) {
    STARTFUNC("IndentNormal{h_c.cpp}");
    int I = 0;
    int Pos, L;

    if (LookAt(B, Line, 0, "case", hsC_Keyword) ||
        LookAt(B, Line, 0, "default", hsC_Keyword))
    {
        I = SearchBackMatch(-1, B, Line - 1, hsC_Normal, "{", "}", &Pos, &L) + C_CASE_OFS;
        return I;
    } else if (LookAt(B, Line, 0, "public:", hsC_Keyword, 0) ||
               LookAt(B, Line, 0, "private:", hsC_Keyword, 0) ||
               LookAt(B, Line, 0, "protected:", hsC_Keyword, 0))
    {
        I = SearchBackMatch(-1, B, Line - 1, hsC_Normal, "{", "}", &Pos, &L) + C_CLASS_OFS;
        return I;
    } else if (LookAt(B, Line, 0, "else", hsC_Keyword)) {
        I = SearchBackMatch(-1, B, Line - 1, hsC_Keyword, "if", "else", &Pos, &L, 1);
        return I;
    } else if (LookAt(B, Line, 0, "}", hsC_Normal, 0)) {
        I = SearchBackMatch(-1, B, Line - 1, hsC_Normal, "{", "}", &Pos, &L, 0, 1);
        return I;
    } else if (LookAt(B, Line, 0, ")", hsC_Normal, 0)) {
        I = SearchBackMatch(-1, B, Line - 1, hsC_Normal, "(", ")", &Pos, &L);
        if (C_PAREN_DELTA >= 0)
            return I + C_PAREN_DELTA;
        else
            return Pos;
    } else if (LookAt(B, Line, 0, "]", hsC_Normal, 0)) {
        I = SearchBackMatch(-1, B, Line - 1, hsC_Normal, "[", "]", &Pos, &L);
        if (C_PAREN_DELTA >= 0)
            return I + C_PAREN_DELTA;
        else
            return Pos;
    } else {
        char CharP = ' ';
        // char FirstCharP = ' ';
        int RowP = Line;
        int ColP = -1;
        int PrevRowP = RowP;
        int PrevColP = ColP;
        int FirstRowP;
        int FirstColP;
        int ContinuationIndent = 0;

        if (SkipWhite(B, Line, PrevRowP, PrevColP, SKIP_BACK) != 1)
            return 0;

        PrevColP++;
        LOG << "PrevRowP=" << PrevRowP << ", PrevColP=" << PrevColP << ENDLINE;

        if (FindPrevIndent(B, RowP, ColP, CharP,
                           FIND_IF |
                           FIND_ELSE |
                           FIND_FOR |
                           FIND_WHILE |
                           FIND_SWITCH |
                           FIND_CASE |
                           //FIND_CLASS |
                           FIND_COLON |
                           FIND_SEMICOLON |
                           FIND_COMMA |
                           FIND_ENDBLOCK) != 1)
        {
            if (RowP != PrevRowP)
                ContinuationIndent = C_CONTINUATION;
            I = 0;
            if (LookAt(B, Line, 0, "{", hsC_Normal, 0)) {
                I += C_BRACE_OFS;
                ContinuationIndent = 0;
            }
            return I + ContinuationIndent;
        }

        FirstRowP = RowP;
        FirstColP = ColP;
        // FirstCharP = CharP;

        LOG << "FirstRowP=" << FirstRowP << ", FirstColP=" << FirstColP <<
            ", CharP=" << BinChar(CharP) << ENDLINE;

        switch (CharP) {
        case 'c':
            I = B->LineIndented(RowP) + C_CONTINUATION;
            return I;

        case '(':
        case '[':
            if (C_PAREN_DELTA >= 0) {
                I = B->LineIndented(FirstRowP) + C_PAREN_DELTA;
            } else {
                ColP++;
                if (SkipWhite(B, Line, RowP, ColP, SKIP_FORWARD | SKIP_LINE) != 1)
                    return 0;
                if (ColP < B->LineChars(RowP) || !FunctionUsesContinuation) {
                    char strLeft[2] = { CharP, 0 };
                    char strRight[2] = { CharP == '(' ? ')' : ']', 0 };
                    I = SearchBackMatch(-1, B, Line - 1, hsC_Normal, strLeft, strRight, &Pos, &L);
                    I = Pos + 1;
                } else {
                    I = B->LineIndented(RowP) + C_CONTINUATION;
                }
            }
            return I;

        case '{':
            ColP++;
            if (((PrevRowP != RowP) ||
                 ((PrevRowP == RowP) && (PrevColP != ColP)))
                && FirstRowP != PrevRowP)
                ContinuationIndent = C_CONTINUATION;
            ColP--; ColP--;
            if (SkipWhite(B, Line, RowP, ColP, SKIP_BACK | SKIP_TOBOL | SKIP_MATCH) != 1)
                return 0;
            I = B->LineIndented(RowP);
            if (B->LineIndented(FirstRowP) <= C_FIRST_WIDTH)
                I += C_FIRST_INDENT;
            else
                I += C_INDENT;
	    PRINTF(("'{' indent : Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));

            if (LookAt(B, Line, 0, "{", hsC_Normal, 0))
                I -= C_BRACE_OFS;
            else
                I += ContinuationIndent;

            return I;
        case ',':
            I = B->LineIndented(FirstRowP);
            return I;
        case '}':
            ColP++;
            ColP++;
            /*---nobreak---*/
        case ';':
            ColP--;
            if (FindPrevIndent(B, RowP, ColP, CharP,
                               ((CharP == ',') ? FIND_COMMA | FIND_COLON :
                                //(CharP == ';') ? FIND_SEMICOLON | FIND_COLON :
                                FIND_SEMICOLON | FIND_COLON)) != 1)
            {
                if (FirstRowP != PrevRowP)
                    ContinuationIndent = C_CONTINUATION;
                I = 0;
                if (LookAt(B, Line, 0, "{", hsC_Normal, 0)) {
                    I += C_BRACE_OFS;
                    ContinuationIndent = 0;
                }
                return I + ContinuationIndent;
            }
            PRINTF(("';' Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));

            LOG << "  CharP now: " << BinChar(CharP) << ENDLINE;
            switch (CharP) {
            case ',':
            case ';':
            case '{':
            case ':':
                ColP++;
                if (SkipWhite(B, Line, RowP, ColP, SKIP_FORWARD) != 1)
                    return 0;
                //ColP--;
                //if (SkipWhite(B, RowP, ColP, SKIP_BACK) != 1)
                //if (CharP == ':') {
                //    I -= C_COLON_OFS;
                //}
                PRINTF(("';' indent : Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));
                I = B->LineIndented(RowP);
                if (((PrevRowP != RowP) ||
                     ((PrevRowP == RowP) && (PrevColP != ColP)))
                    && FirstRowP != PrevRowP)
                    ContinuationIndent = C_CONTINUATION;

                if (LookAt(B, Line, 0, "{", hsC_Normal, 0)) {
                    //I -= C_BRACE_OFS;
                    ContinuationIndent = 0;
                }
                if (LookAt(B, Line, 0, "{", hsC_Normal, 0)
                    && LookAt(B, RowP, ColP, "{", hsC_Normal, 0))
                    I -= 0; //C_BRACE_OFS;
                else if (LookAt(B, Line, 0, "{", hsC_Normal, 0)
                         && !LookAt(B, RowP, ColP, "{", hsC_Normal, 0))
                    I += C_BRACE_OFS;
                else if (!LookAt(B, Line, 0, "{", hsC_Normal, 0)
                         && LookAt(B, RowP, ColP, "{", hsC_Normal, 0))
                    I -= C_BRACE_OFS;
                break;
            case '(':
                ColP++;
                if (SkipWhite(B, Line, RowP, ColP, SKIP_FORWARD | SKIP_LINE) != 1)
                    return 0;
                I = B->ScreenPos(B->RLine(RowP), ColP);
                break;
            default:
                I = B->LineIndented(RowP);
                break;
            }
            PRINTF(("';' -- indent : Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));

            //            else
            //            if (LookAt(B, Line, 0, "{", hsC_Normal, 0))
            //                I += C_INDENT - C_BRACE_OFS;

            return I + ContinuationIndent;

        case ':':
	    ColP--;
            PRINTF(("COL-- %d\n", ColP));
	    if (FindPrevIndent(B, RowP, ColP, CharP,
			       FIND_SEMICOLON | FIND_COLON | FIND_QUESTION
			       | FIND_CLASS | FIND_CASE) != 1) {
		PRINTF(("FOUNPRE \n"));
                if (FirstRowP != PrevRowP)
                    ContinuationIndent = C_CONTINUATION;
                return 0 + ContinuationIndent;
            }

            PRINTF(("':' Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));

            switch (CharP) {
            case ':':
                //ColP++;
                /*if (SkipWhite(B, Line, RowP, ColP, SKIP_FORWARD) != 1)
                 return 0;
                 I = B->LineIndented(RowP);// - C_COLON_OFS;
                 PRINTF(("':' 0 indent : Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));
                 break;*/
            case '{':
            case ';':
                ColP++;
                if (SkipWhite(B, Line, RowP, ColP, SKIP_FORWARD) != 1)
                    return 0;
                I = B->LineIndented(RowP);
                PRINTF(("!!! FirstRowP=%d, PrevRowP=%d, RowP=%d, I=%d\n", FirstRowP, PrevRowP, RowP, I));
                PRINTF(("!!! FirstColP=%d, PrevColP=%d, ColP=%d\n", FirstColP, PrevColP, ColP));
                if (CheckLabel(B, RowP))
                    I -= C_COLON_OFS;
                else if (PrevRowP == RowP && FirstRowP == PrevRowP && FirstColP + 1 == PrevColP)
                    I += C_CONTINUATION;
                if (LookAt(B, Line, 0, "{", hsC_Normal, 0)
                    && LookAt(B, RowP, ColP, "{", hsC_Normal, 0))
                    I -= 0;//C_BRACE_OFS;
                else if (LookAt(B, Line, 0, "{", hsC_Normal, 0)
                         && !LookAt(B, RowP, ColP, "{", hsC_Normal, 0))
                    I += C_BRACE_OFS;
                else if (!LookAt(B, Line, 0, "{", hsC_Normal, 0)
                         && LookAt(B, RowP, ColP, "{", hsC_Normal, 0))
                    I -= C_BRACE_OFS;
                PRINTF(("':' 1 indent : Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));
                break;
            case 'p':
                ColP++;
                //if (SkipWhite(B, Line, RowP, ColP, SKIP_FORWARD) != 1)
                //                    return 0;
                I = B->LineIndented(RowP) + C_CLASS_DELTA;
                //                if (FirstRowP == RowP) {
                //                    I += C_CLASS_DELTA;
                ///                if (LookAt(B, Line, 0, "{", hsC_Normal, 0)) {
                ///                    I += C_INDENT - C_BRACE_OFS;
                ///                }
                //                }
                PRINTF(("':' 2 indent : Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));
                break;
            case 'l':
                ColP++;
                I = B->LineIndented(RowP) + C_BRACE_OFS;
                //C_CLASS_OFS + C_CLASS_DELTA;
                break;
            case 'c':
                ColP++;
                //                if (SkipWhite(B, Line, RowP, ColP, SKIP_FORWARD) != 1)
                //                    return 0;
                I = B->LineIndented(RowP) + C_CASE_DELTA;
                //                if (FirstRowP == RowP) {
                //                    I += C_CASE_DELTA;
                ///                if (LookAt(B, Line, 0, "{", hsC_Normal, 0)) {
                ///                        I += C_INDENT - C_BRACE_OFS;
                ///                }
                //                }

                PRINTF(("':' 3 indent : Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));
                break;
            default:
                I = B->LineIndented(RowP);
                break;
            }
            if (((PrevRowP != RowP) ||
                 ((PrevRowP == RowP) && (PrevColP != ColP)))
                && FirstRowP != PrevRowP)
                ContinuationIndent = C_CONTINUATION;
            if (LookAt(B, Line, 0, "{", hsC_Normal, 0)) {
                //I -= C_INDENT - C_BRACE_OFS;
                ContinuationIndent = 0;
            }
            PRINTF(("':' -- indent : Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));
            return I + ContinuationIndent;

        case 'i':
        case 's':
        case 'f':
        case 'e':
        case 'w':
            I = B->LineIndented(RowP);
            switch (CharP) {
            case 'i': ColP += 2; break; // if
            case 'f': ColP += 3; break; // for
            case 'e': ColP += 4; break; // else
            case 'w': ColP += 5; break; // while
            case 's': ColP += 6; break;
            }
            PRINTF(("'ifews' -- indent 1: Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));
            if (SkipWhite(B, Line, RowP, ColP,
                          SKIP_FORWARD | (CharP != 'e' ? SKIP_MATCH : 0)) != 1)
                return 0;
            if (RowP >= Line) {
                RowP = Line;
                ColP = -1;
            } else
                ColP--;
            if (SkipWhite(B, Line, RowP, ColP, SKIP_BACK) != 1)
                return 0;
            ColP++;
            PRINTF(("'ifews' -- indent 2: Line=%d, RowP=%d, ColP=%d, CharP=%c\n", Line, RowP, ColP, CharP));

            if (((PrevRowP != RowP) ||
                 ((PrevRowP == RowP) && (PrevColP != ColP)))
                && FirstRowP != PrevRowP)
                ContinuationIndent = C_CONTINUATION;

            I += C_INDENT;

            if (LookAt(B, Line, 0, "{", hsC_Normal, 0)) {
                I -= C_INDENT - C_BRACE_OFS;
                ContinuationIndent = 0;
            }

            return I + ContinuationIndent;

        // default: return 0;
        }
    }
    return 0;
}
Example #15
0
int Indent_C(EBuffer *B, int Line, int PosCursor) {
    int I;
    hsState *StateMap = NULL;
    int StateLen = 0;
    int OI;

    OI = I = B->LineIndented(Line);
    if (Line == 0) {
        I = 0;
    } else {
        if (I != 0) B->IndentLine(Line, 0);
        if (B->GetMap(Line, &StateLen, &StateMap) == 0) return 0;

        switch (B->RLine(Line - 1)->StateE) {
        case hsC_Comment:
        case hsC_CPP_Comm:
            I = IndentComment(B, Line, StateLen, StateMap);
            break;
        case hsC_CPP:
            /*case hsC_CPP_Comm:*/
        case hsC_CPP_String1:
        case hsC_CPP_String2:
        case hsC_CPP_ABrace:
            I = C_INDENT;
            break;
        default:
            if (StateLen > 0) {                 // line is not empty
                if (StateMap[0] == hsC_CPP || StateMap[0] == hsC_CPP_Comm ||
                    StateMap[0] == hsC_CPP_String1 || StateMap[0] == hsC_CPP_String2 ||
                    StateMap[0] == hsC_CPP_ABrace)
                {
                    I = IndentCPP(B, Line, StateLen, 0);
                } else {
                    I = IndentNormal(B, Line, StateLen, StateMap);
		    if ((StateMap[0] == hsC_Comment
			 || StateMap[0] == hsC_CommentL
			 || StateMap[0] == hsC_CPP_Comm)
			&& ((LookAt(B, Line, 0, "/*", hsC_Comment, 0)
                             || LookAt(B, Line, 0, "/*", hsC_CPP_Comm, 0)
                             || LookAt(B, Line, 0, "//", hsC_CommentL, 0))))
                    {
                        I += C_COMMENT_OFS;
                    } else if (CheckLabel(B, Line)) {
                        if (LookAt(B, Line, 0, "case", hsC_Keyword) ||
                            LookAt(B, Line, 0, "default", hsC_Keyword) ||
                            LookAt(B, Line, 0, "public:", hsC_Keyword, 0) ||
                            LookAt(B, Line, 0, "private:", hsC_Keyword, 0) ||
                            LookAt(B, Line, 0, "protected:", hsC_Keyword, 0))
                            ;
                        else
                            I += C_COLON_OFS;
                    } //else if (LookAt(B, Line, 0, "{", hsC_Normal, 0)) {
                    //    I -= C_INDENT - C_BRACE_OFS;
                    //}
                }
            } else {
                I = IndentNormal(B, Line, 0, NULL);
            }
            break;
        }
    }
    if (StateMap)
        free(StateMap);
    if (I >= 0)
        B->IndentLine(Line, I);
    else
        I = 0;
    if (PosCursor == 1) {
        int X = B->CP.Col;

        X = X - OI + I;
        if (X < I) X = I;
        if (X < 0) X = 0;
        if (X > B->LineLen(Line)) {
            X = B->LineLen(Line);
            if (X < I) X = I;
        }
        if (B->SetPosR(X, Line) == 0) return 0;
    } else if (PosCursor == 2) {
        if (B->SetPosR(I, Line) == 0) return 0;
    }
    return 1;
}