示例#1
0
//TODO: Needs header, comments
Message Connection::receiveMessage() {
	std::fstream bufferFileStream;
	mutexForBufferFile->lock();//Make sure to lock the mutexForBufferFile so others can't write to it while we're looking at it
	bufferFileStream.open(IPAddress, std::ios::in | std::ios::out);//Open the file with the filename = IPAddress (the IP address of the connection). If it does not exist yet, create it.

	//Create some buffers to hold the data
	unsigned char source[constants::VID_SIZE];//This will hold the source VID
	unsigned char dest[constants::VID_SIZE];//This will hold the destination VID
	bool flag;//This will hold the broadcast flag
	char m[constants::MAX_MESSAGE_SIZE];//This will hold the message's content

	//Grab the first byte from the file
	unsigned char x;
	bufferFileStream >> x;
	int i = 0;

	while (!((x == EOF) || (x == '\0'))) {//While there are still bytes to be read from the file, and we do not encounter a  '\0' (used to deliniate the messages in the file)...

		if (i < constants::VID_SIZE)
			source[i] = x;//Put this byte in the source
		else if (i < (2 * constants::VID_SIZE))
			dest[i] = x;//Put this byte in the destination
		else if (i == (2 * constants::VID_SIZE))
			flag = (x != 0);//This byte is the broadcast flag
		else
			m[i] = x;//Put this byte in the message's content

		i++;
		bufferFileStream >> x;
	}

	Message toReturn = Message(source, dest, flag, m);//Use the now filled buffers to create a message

	//Find the length of the buffer file
	int endOfMessage = bufferFileStream.tellg();
	bufferFileStream.seekg(0, bufferFileStream.end);
	int lengthOfFile = bufferFileStream.tellg();

	//Find the length of the file after the first message (now read into "toReturn")
	int lengthOfRemaining = lengthOfFile - endOfMessage;

	//Grab the file's contents *after* the message we've already read in
	unsigned char remainingBuffer[lengthOfRemaining];

	bufferFileStream.seekg(lengthOfFile);

	char y;
	bufferFileStream >> y;
	int j = 0;

	while (!(j == EOF)) {
		remainingBuffer[j] = y;
		j++;
		bufferFileStream >> y;
	}

	bufferFileStream.close();//Close the file so we can open it again in truncuate (over -write) mode
	bufferFileStream.open(IPAddress, std::ios::out | std::ios::trunc);//Open the file with the filename = IPAddress (the IP address of the connection) in overwrite mode

	for (j = 0; j < lengthOfRemaining; j++)
		bufferFileStream << remainingBuffer[j];//Write only the contents of the file *after* the message we converted to overwrite the message we converted

	bufferFileStream.close(); //Close the file so others can use it

	mutexForBufferFile->unlock();//Unlock the mutexForBufferFile so that others know the file is availible

	return toReturn;//Return the newly created message
}
示例#2
0
//*****************************************************************************
//
//!    Clear the console window
//!
//! This function
//!        1. clears the console window.
//!
//! \return none
//
//*****************************************************************************
void 
ClearTerm()
{
    Message("\33[2J\r");
}
示例#3
0
std::shared_ptr<Notifications> ClientImpl::PING(in_addr_t ip, uint16_t port) {
  ILOG << "Sending ping request to the server\n";
  return sendRequest(ip, port, Message(Type::Confirmable, messageId_++, Code::Empty, newToken(), ""));
}
示例#4
0
BOOL GeneralTab_OnApply (HWND hDlg, BOOL fForce, BOOL fComplainIfInvalid)
{
   if (!fForce)
      {
      // Don't try to do anything if we've already failed the apply
      if (GetWindowLongPtr (hDlg, DWLP_MSGRESULT))
         return FALSE;
      }

   // If the user has changed CellServDB, configuration parameters for
   // the driver or anything else, we want to commit those changes first.
   // We *won't* commit server prefs changes yet, because we haven't yet
   // checked to see if the service is running.
   //
   if (!HostsTab_CommitChanges (fForce))
      return FALSE;

   if (!AdvancedTab_CommitChanges (fForce))
      return FALSE;

   if (!GeneralTab_VerifyOK (hDlg, fComplainIfInvalid))
      return FALSE;

   TCHAR szText[ MAX_PATH ];

   if (g.fIsWinNT)
      {
      GetDlgItemText (hDlg, IDC_CELL, szText, MAX_PATH);
      if (lstrcmpi (szText, g.Configuration.szCell))
         {
         if (!Config_SetCellName (szText))
            return FALSE;
         lstrcpy (g.Configuration.szCell, szText);
         }
      }

   BOOL fLogonAuthent = IsDlgButtonChecked (hDlg, IDC_LOGON);
   if (fLogonAuthent != g.Configuration.fLogonAuthent)
      {
	   SetBitLogonOption(fLogonAuthent,LOGON_OPTION_INTEGRATED);
      g.Configuration.fLogonAuthent = fLogonAuthent;
      }

   Config_SetTrayIconFlag (IsDlgButtonChecked (hDlg, IDC_TRAYICON));

   if (g.fIsWinNT)
      {
      BOOL fBeGateway = IsDlgButtonChecked (hDlg, IDC_GATEWAY);
      if (fBeGateway != g.Configuration.fBeGateway)
         {
         if (!Config_SetGatewayFlag (fBeGateway))
            return FALSE;
         g.fNeedRestart = TRUE;
         g.Configuration.fBeGateway = fBeGateway;
         }
      }
   else // (!g.fIsWinNT)
      {
      GetDlgItemText (hDlg, IDC_GATEWAY, szText, MAX_PATH);
      if (lstrcmpi (szText, g.Configuration.szGateway))
         {
         TCHAR szNewCell[ MAX_PATH ];
         if (!Config_ContactGateway (szText, szNewCell))
            {
            Message (MB_ICONASTERISK | MB_OK, GetErrorTitle(), IDS_BADGATEWAY_DESC);
            return FALSE;
            }

         if (!GeneralTab_VerifyCell (hDlg, fComplainIfInvalid, szNewCell))
            return FALSE;

         if (!Config_SetGatewayName (szText))
            return FALSE;

         if (!Config_SetCellName (szNewCell))
            return FALSE;

         Config_FixGatewayDrives();

         SetDlgItemText (hDlg, IDC_CELL, szNewCell);
         lstrcpy (g.Configuration.szGateway, szText);
         lstrcpy (g.Configuration.szCell, szNewCell);

         GeneralTab_OnGateway (hDlg);
         }
      }

   return TRUE;
}
 void exit(status_t result) {
     this->result = result;
     exitPending = true;
     looper->sendMessage(this, Message(MSG_EXIT));
 }
示例#6
0
文件: vendor.c 项目: jpmatsci/pcb
/* for a given drill size, find the closest vendor drill size */
int
vendorDrillMap (int in)
{
  int i, min, max;

  if (in == cached_drill)
    return cached_map;
  cached_drill = in;

  /* skip the mapping if we don't have a vendor drill table */
  if ((n_vendor_drills == 0) || (vendor_drills == NULL)
      || (vendorMapEnable == false))
    {
      cached_map = in;
      return in;
    }

  /* are we smaller than the smallest drill? */
  if (in <= vendor_drills[0])
    {
      cached_map = vendor_drills[0];
      return vendor_drills[0];
    }

  /* are we larger than the largest drill? */
  if (in > vendor_drills[n_vendor_drills - 1])
    {
      Message (_("Vendor drill list does not contain a drill >= %6.2f mil\n"
		 "Using %6.2f mil instead.\n"),
	       0.01 * in, 0.01 * vendor_drills[n_vendor_drills - 1]);
      cached_map = vendor_drills[n_vendor_drills - 1];
      return vendor_drills[n_vendor_drills - 1];
    }

  /* figure out which 2 drills are closest in size */
  min = 0;
  max = n_vendor_drills - 1;
  while (max - min > 1)
    {
      i = (max+min) / 2;
      if (in > vendor_drills[i])
	min = i;
      else
	max = i;
    }
  i = max;

  /* now round per the rounding mode */
  if (rounding_method == CLOSEST)
    {
      /* find the closest drill size */
      if ((in - vendor_drills[i - 1]) > (vendor_drills[i] - in))
	{
	  cached_map = vendor_drills[i];
	  return vendor_drills[i];
	}
      else
	{
	  cached_map = vendor_drills[i - 1];
	  return vendor_drills[i - 1];
	}
    }
  else
    {
      /* always round up */
      cached_map = vendor_drills[i];
      return vendor_drills[i];
    }

}
示例#7
0
文件: vendor.c 项目: jpmatsci/pcb
bool
vendorIsElementMappable (ElementType *element)
{
  int i;
  int noskip;

  if (vendorMapEnable == false)
    return false;

  noskip = 1;
  for (i = 0; i < n_refdes; i++)
    {
      if ((NSTRCMP (UNKNOWN (NAMEONPCB_NAME (element)), ignore_refdes[i]) ==
	   0)
	  || rematch (ignore_refdes[i], UNKNOWN (NAMEONPCB_NAME (element))))
	{
	  Message (_
		   ("Vendor mapping skipped because refdes = %s matches %s\n"),
		   UNKNOWN (NAMEONPCB_NAME (element)), ignore_refdes[i]);
	  noskip = 0;
	}
    }
  if (noskip)
    for (i = 0; i < n_value; i++)
      {
	if ((NSTRCMP (UNKNOWN (VALUE_NAME (element)), ignore_value[i]) == 0)
	    || rematch (ignore_value[i], UNKNOWN (VALUE_NAME (element))))
	  {
	    Message (_
		     ("Vendor mapping skipped because value = %s matches %s\n"),
		     UNKNOWN (VALUE_NAME (element)), ignore_value[i]);
	    noskip = 0;
	  }
      }

  if (noskip)
    for (i = 0; i < n_descr; i++)
      {
	if ((NSTRCMP (UNKNOWN (DESCRIPTION_NAME (element)), ignore_descr[i])
	     == 0)
	    || rematch (ignore_descr[i],
			UNKNOWN (DESCRIPTION_NAME (element))))
	  {
	    Message (_
		     ("Vendor mapping skipped because descr = %s matches %s\n"),
		     UNKNOWN (DESCRIPTION_NAME (element)), ignore_descr[i]);
	    noskip = 0;
	  }
      }

  if (noskip && TEST_FLAG (LOCKFLAG, element))
    {
      Message (_("Vendor mapping skipped because element %s is locked\n"),
	       UNKNOWN (NAMEONPCB_NAME (element)));
      noskip = 0;
    }

  if (noskip)
    return true;
  else
    return false;
}
示例#8
0
Int2 Main (void)

{
  Char            app [64], type;
  CSpeedFlagData  cfd;
  CharPtr         directory, filter, infile, logfile, outfile, str, suffix;
  Boolean         remote;
  time_t          runtime, starttime, stoptime;

  /* standard setup */

  ErrSetFatalLevel (SEV_MAX);
  ErrClearOptFlags (EO_SHOW_USERSTR);
  UseLocalAsnloadDataAndErrMsg ();
  ErrPathReset ();

  /* finish resolving internal connections in ASN.1 parse tables */

  if (! AllObjLoad ()) {
    Message (MSG_FATAL, "AllObjLoad failed");
    return 1;
  }
  if (! SubmitAsnLoad ()) {
    Message (MSG_FATAL, "SubmitAsnLoad failed");
    return 1;
  }
  if (! FeatDefSetLoad ()) {
    Message (MSG_FATAL, "FeatDefSetLoad failed");
    return 1;
  }
  if (! SeqCodeSetLoad ()) {
    Message (MSG_FATAL, "SeqCodeSetLoad failed");
    return 1;
  }
  if (! GeneticCodeTableLoad ()) {
    Message (MSG_FATAL, "GeneticCodeTableLoad failed");
    return 1;
  }

  /* process command line arguments */

  sprintf (app, "cspeedtest %s", CSPEEDTEST_APPLICATION);
  if (! GetArgs (app, sizeof (myargs) / sizeof (Args), myargs)) {
    return 0;
  }

  MemSet ((Pointer) &cfd, 0, sizeof (CSpeedFlagData));

  directory = (CharPtr) myargs [p_argInputPath].strvalue;
  infile = (CharPtr) myargs [i_argInputFile].strvalue;
  outfile = (CharPtr) myargs [o_argOutputFile].strvalue;
  filter = (CharPtr) myargs [f_argFilter].strvalue;
  suffix = (CharPtr) myargs [x_argSuffix].strvalue;

  cfd.batch = FALSE;
  cfd.binary = (Boolean) myargs [b_argBinary].intvalue;
  cfd.compressed = (Boolean) myargs [c_argCompressed].intvalue;
  cfd.lock = (Boolean) myargs [l_argLockFar].intvalue;
  cfd.type = 1;

  str = myargs [a_argType].strvalue;
  TrimSpacesAroundString (str);
  if (StringDoesHaveText (str)) {
    type = str [0];
  } else {
    type = 'a';
  }

  type = TO_LOWER (type);
  switch (type) {
    case 'a' :
      cfd.type = 1;
      break;
    case 'e' :
      cfd.type = 2;
      break;
    case 'b' :
      cfd.type = 3;
      break;
    case 's' :
      cfd.type = 4;
      break;
    case 'm' :
      cfd.type = 5;
      break;
    case 't' :
      cfd.type = 1;
      cfd.batch = TRUE;
      break;
    case 'f' :
      cfd.type = 6;
      break;
    case 'l' :
      cfd.type = 7;
      break;
    default :
      cfd.type = 1;
      break;
  }

  remote = (Boolean) myargs [R_argRemote].intvalue;

  cfd.maxcount = myargs [X_argMaxCount].intvalue;
  if (cfd.maxcount < 1) {
    cfd.maxcount = 1;
  }

  cfd.io = myargs [O_argInOut].strvalue;
  cfd.clean = myargs [K_argClean].strvalue;
  cfd.skip = myargs [P_argSkip].strvalue;
  cfd.index = myargs [I_argIndex].strvalue;
  cfd.seq = myargs [S_argSeq].strvalue;
  cfd.feat = myargs [F_argFeat].strvalue;
  cfd.desc = myargs [D_argDesc].strvalue;
  cfd.verify = myargs [V_argVerify].strvalue;

  cfd.amp = AsnAllModPtr ();
  cfd.atp_bss = AsnFind ("Bioseq-set");
  cfd.atp_bsss = AsnFind ("Bioseq-set.seq-set");
  cfd.atp_se = AsnFind ("Bioseq-set.seq-set.E");
  cfd.atp_bsc = AsnFind ("Bioseq-set.class");
  cfd.bssp_atp = AsnLinkType (NULL, cfd.atp_bss);

  logfile = (CharPtr) myargs [L_argLogFile].strvalue;
  if (StringDoesHaveText (logfile)) {
    cfd.logfp = FileOpen (logfile, "w");
  }

  if (remote) {
    PubSeqFetchEnable ();
  }

  if (StringDoesHaveText (outfile)) {
    cfd.ofp = FileOpen (outfile, "w");
  }

  starttime = GetSecs ();

  if (StringDoesHaveText (directory)) {

    DirExplore (directory, NULL, suffix, FALSE, ProcessOneRecord, (Pointer) &cfd);

  } else if (StringDoesHaveText (infile)) {

    ProcessOneRecord (infile, (Pointer) &cfd);
  }

  if (cfd.ofp != NULL) {
    FileClose (cfd.ofp);
  }

  stoptime = GetSecs ();
  runtime = stoptime - starttime;
  if (cfd.logfp != NULL) {
    fprintf (cfd.logfp, "Finished in %ld seconds\n", (long) runtime);
    FileClose (cfd.logfp);
  }
  printf ("Finished in %ld seconds\n", (long) runtime);

  if (remote) {
    PubSeqFetchDisable ();
  }

  return 0;
}
示例#9
0
static void ProcessSingleRecord (
  CharPtr filename,
  CSpeedFlagPtr cfp
)

{
  AsnIoPtr      aip;
  BioseqPtr     bsp;
  ValNodePtr    bsplist = NULL;
  BioseqSetPtr  bssp;
  Pointer       dataptr = NULL;
  Uint2         datatype, entityID = 0;
  FileCache     fc;
  FILE          *fp;
  Int1          iotype;
  Char          line [512];
  Int4          maxio = 1;
  SeqEntryPtr   sep;
  time_t        starttime, stoptime, worsttime;
  CharPtr       str;
  Int4          x;

  if (cfp == NULL) return;

  if (StringHasNoText (filename)) return;

  if (StringChr (cfp->io, 'r') != NULL) {
    maxio = cfp->maxcount;
  }

  starttime = GetSecs ();

  for (x = 0; x < maxio; x++) {
    if (entityID != 0) {
      ObjMgrFreeByEntityID (entityID);
      entityID = 0;
      dataptr = NULL;
    }

    if (cfp->type == 1) {

      fp = FileOpen (filename, "r");
      if (fp == NULL) {
        Message (MSG_POSTERR, "Failed to open '%s'", filename);
        return;
      }

      dataptr = ReadAsnFastaOrFlatFile (fp, &datatype, NULL, FALSE, FALSE, FALSE, FALSE);

      FileClose (fp);

      entityID = ObjMgrRegister (datatype, dataptr);

    } else if (cfp->type >= 2 && cfp->type <= 5) {

      aip = AsnIoOpen (filename, cfp->binary? "rb" : "r");
      if (aip == NULL) {
        Message (MSG_POSTERR, "AsnIoOpen failed for input file '%s'", filename);
        return;
      }

      switch (cfp->type) {
        case 2 :
          dataptr = (Pointer) SeqEntryAsnRead (aip, NULL);
          datatype = OBJ_SEQENTRY;
          break;
        case 3 :
          dataptr = (Pointer) BioseqAsnRead (aip, NULL);
          datatype = OBJ_BIOSEQ;
          break;
        case 4 :
          dataptr = (Pointer) BioseqSetAsnRead (aip, NULL);
          datatype = OBJ_BIOSEQSET;
          break;
        case 5 :
          dataptr = (Pointer) SeqSubmitAsnRead (aip, NULL);
          datatype = OBJ_SEQSUB;
          break;
        default :
          break;
      }

      AsnIoClose (aip);

      entityID = ObjMgrRegister (datatype, dataptr);

    } else if (cfp->type == 6) {

      fp = FileOpen (filename, "r");
      if (fp == NULL) {
        Message (MSG_POSTERR, "Failed to open '%s'", filename);
        return;
      }

      dataptr = ReadAsnFastaOrFlatFile (fp, &datatype, NULL, FALSE, FALSE, FALSE, FALSE);

      FileClose (fp);

      entityID = ObjMgrRegister (datatype, dataptr);

    } else if (cfp->type == 7) {

      fp = FileOpen (filename, "r");
      if (fp == NULL) {
        Message (MSG_POSTERR, "Failed to open '%s'", filename);
        return;
      }

      FileCacheSetup (&fc, fp);

      str = FileCacheReadLine (&fc, line, sizeof (line), NULL);
      while (str != NULL) {
        str = FileCacheReadLine (&fc, line, sizeof (line), NULL);
      }

      FileClose (fp);

      return;

    } else {
      Message (MSG_POSTERR, "Input format type '%d' unrecognized", (int) cfp->type);
      return;
    }
  }

  if (entityID < 1 || dataptr == NULL) {
    Message (MSG_POSTERR, "Data read failed for input file '%s'", filename);
    return;
  }

  if (datatype == OBJ_SEQSUB || datatype == OBJ_SEQENTRY ||
        datatype == OBJ_BIOSEQ || datatype == OBJ_BIOSEQSET) {

    stoptime = GetSecs ();
    worsttime = stoptime - starttime;
    if (cfp->logfp != NULL) {
      fprintf (cfp->logfp, "ASN reading time %ld seconds\n", (long) worsttime);
      fflush (cfp->logfp);
    }

    sep = GetTopSeqEntryForEntityID (entityID);

    if (sep == NULL) {
      sep = SeqEntryNew ();
      if (sep != NULL) {
        if (datatype == OBJ_BIOSEQ) {
          bsp = (BioseqPtr) dataptr;
          sep->choice = 1;
          sep->data.ptrvalue = bsp;
          SeqMgrSeqEntry (SM_BIOSEQ, (Pointer) bsp, sep);
        } else if (datatype == OBJ_BIOSEQSET) {
          bssp = (BioseqSetPtr) dataptr;
          sep->choice = 2;
          sep->data.ptrvalue = bssp;
          SeqMgrSeqEntry (SM_BIOSEQSET, (Pointer) bssp, sep);
        } else {
          sep = SeqEntryFree (sep);
        }
      }
      sep = GetTopSeqEntryForEntityID (entityID);
    }

    if (sep != NULL) {

      if (cfp->lock) {
        starttime = GetSecs ();

        bsplist = LockFarComponents (sep);

        stoptime = GetSecs ();
        worsttime = stoptime - starttime;
        if (cfp->logfp != NULL) {
          fprintf (cfp->logfp, "Far component locking time %ld seconds\n", (long) worsttime);
          fflush (cfp->logfp);
        }
      }

      if (StringChr (cfp->io, 'w') != NULL) {
        starttime = GetSecs ();

        iotype = ASNIO_TEXT_OUT;
        if (StringChr (cfp->io, 'b') != NULL) {
          iotype = ASNIO_BIN_OUT;
        }

        for (x = 0; x < cfp->maxcount; x++) {
          aip = AsnIoNew (iotype, cfp->ofp, NULL, NULL, NULL);
          if (aip != NULL) {
            SeqEntryAsnWrite (sep, aip, NULL);
            AsnIoFree (aip, FALSE);
          }
        }

        stoptime = GetSecs ();
        worsttime = stoptime - starttime;
        if (cfp->logfp != NULL) {
          fprintf (cfp->logfp, "ASN writing time %ld seconds\n", (long) worsttime);
          fflush (cfp->logfp);
        }
      }

      starttime = GetSecs ();

      for (x = 0; x < cfp->maxcount; x++) {
        DoProcess (sep, entityID, cfp);
      }

      stoptime = GetSecs ();
      worsttime = stoptime - starttime;
      if (cfp->logfp != NULL) {
        fprintf (cfp->logfp, "Internal processing time %ld seconds\n", (long) worsttime);
        fflush (cfp->logfp);
      }

      ObjMgrFreeByEntityID (entityID);

      bsplist = UnlockFarComponents (bsplist);
    }

  } else {

    Message (MSG_POSTERR, "Datatype %d not recognized", (int) datatype);
  }
}
示例#10
0
/*
 * Given a polygon and a side of it (a direction north/northeast/etc), find
 * a line tangent to that side, offset by clearance, and return it as a
 * pair of vectors PQ.
 * Make it long so it will intersect everything in the area.
 */
static void
POLYAREA_findXmostLine(POLYAREA *a, int side, Vector p, Vector q, int clearance)
{
	p[0] = p[1] = 0;
	q[0] = q[1] = 0;
	int extra = a->contours->xmax - a->contours->xmin +
		    a->contours->ymax - a->contours->ymin;

	switch (side) {
	case NORTH:
		p[1] = q[1] = a->contours->ymin - clearance;
		p[0] = a->contours->xmin - extra;
		q[0] = a->contours->xmax + extra;
		break;
	case SOUTH:
		p[1] = q[1] = a->contours->ymax + clearance;
		p[0] = a->contours->xmin - extra;
		q[0] = a->contours->xmax + extra;
		break;
	case EAST:
		p[0] = q[0] = a->contours->xmax + clearance;
		p[1] = a->contours->ymin - extra;
		q[1] = a->contours->ymax + extra;
		break;
	case WEST:
		p[0] = q[0] = a->contours->xmin - clearance;
		p[1] = a->contours->ymin - extra;
		q[1] = a->contours->ymax + extra;
		break;
	default: {			/* diagonal case */
		int kx, ky, minmax, dq, ckx, cky;
		Coord mm[2] = {MAX_COORD, -MAX_COORD};
		Vector mmp[2];
		VNODE *v;

		switch (side) {
		case NORTHWEST:
			kx = 1;		/* new_x = kx * x + ky * y */
			ky = 1;
			dq = -1;	/* extend line in +x, dq*y */
			ckx = cky = -1;	/* clear line in ckx*clear, cky*clear */
			minmax = 0;	/* min or max */
			break;
		case SOUTHWEST:
			kx = 1;
			ky = -1;
			dq = 1;
			ckx = -1;
			cky = 1;
			minmax = 0;
			break;
		case NORTHEAST:
			kx = 1;
			ky = -1;
			dq = 1;
			ckx = 1;
			cky = -1;
			minmax = 1;
			break;
		case SOUTHEAST:
			kx = ky = 1;
			dq = -1;
			ckx = cky = 1;
			minmax = 1;
			break;
		default:
			Message("bjj: aiee, what side?");
			return;
		}
		v = &a->contours->head;
		do {
			int test = kx * v->point[0] + ky * v->point[1];
			if (test < mm[0]) {
				mm[0] = test;
				mmp[0][0] = v->point[0];
				mmp[0][1] = v->point[1];
			}
			if (test > mm[1]) {
				mm[1] = test;
				mmp[1][0] = v->point[0];
				mmp[1][1] = v->point[1];
			}
		} while ((v = v->next) != &a->contours->head);
		Vcpy2(p, mmp[minmax]);
		/* add clearance in the right direction */
		clearance *= 0.707123;	/* = cos(45) = sqrt(2)/2 */
		p[0] += ckx * clearance;
		p[1] += cky * clearance;
		/* now create a tangent line to that point */
		Vcpy2(q, p);
		p[0] += -extra;
		p[1] += -extra * dq;
		q[0] += extra;
		q[1] += extra * dq;
	}
	}
}
示例#11
0
Int2 Main (void)

{
  AsnIoPtr    aip;
  AsnTypePtr  atp;
  FILE        *dfp = NULL;
  Boolean     do_nuc = FALSE;
  Boolean     do_prot = FALSE;
  XtraPtr     extra;
  FILE        *fp;
  GBSeq       gbsq;
  GBSet       gbst;
  Boolean     get_var;
  Char        line [256];
  Boolean     only_new;
  CharPtr     str;
  Char        xmlbuf [128];
  XtraBlock   xtra;

  ErrSetFatalLevel (SEV_MAX);
  ErrClearOptFlags (EO_SHOW_USERSTR);
  UseLocalAsnloadDataAndErrMsg ();
  ErrPathReset ();

  if (! AllObjLoad ()) {
    Message (MSG_FATAL, "AllObjLoad failed");
    return 1;
  }
  if (! SubmitAsnLoad ()) {
    Message (MSG_FATAL, "SubmitAsnLoad failed");
    return 1;
  }
  if (! SeqCodeSetLoad ()) {
    Message (MSG_FATAL, "SeqCodeSetLoad failed");
    return 1;
  }
  if (! GeneticCodeTableLoad ()) {
    Message (MSG_FATAL, "GeneticCodeTableLoad failed");
    return 1;
  }
  if (! objgbseqAsnLoad ()) {
    Message (MSG_POSTERR, "objgbseqAsnLoad failed");
    return 1;
  }

  if (! GetArgs ("gbseqget", sizeof (myargs) / sizeof (Args), myargs)) {
    return 0;
  }

  fp = FileOpen (myargs [i_argInputFile].strvalue, "r");
  if (fp == NULL) {
    return 1;
  }

  if (! StringHasNoText (myargs [d_argDateFile].strvalue)) {
    dfp = FileOpen (myargs [d_argDateFile].strvalue, "r");
    if (dfp == NULL) {
      return 1;
    }
  }

  if (GetAppParam ("NCBI", "SETTINGS", "XMLPREFIX", NULL, xmlbuf, sizeof (xmlbuf))) {
    AsnSetXMLmodulePrefix (StringSave (xmlbuf));
  }

  MemSet ((Pointer) &xtra, 0, sizeof (XtraBlock));
  MemSet ((Pointer) &gbsq, 0, sizeof (GBSeq));
  xtra.gbseq = &gbsq;
  aip = AsnIoOpen (myargs [o_argOutputFile].strvalue, "wx");

  if (aip == NULL) {
    Message (MSG_POSTERR, "AsnIoOpen failed");
    FileClose (fp);
    return 1;
  }

  only_new = (Boolean) myargs [n_argNewRecords].intvalue;
  get_var = (Boolean) myargs [v_argVariations].intvalue;

  str = myargs [m_argMolecule].strvalue;
  if (StringICmp (str, "n") == 0) {
    do_nuc = TRUE;
  } else if (StringICmp (str, "p") == 0) {
    do_prot = TRUE;
  } else if (StringICmp (str, "b") == 0) {
    do_nuc = TRUE;
    do_prot = TRUE;
  } else {
    do_nuc = TRUE;
  }

  PubSeqFetchEnable ();

  xtra.aip = aip;
  atp = AsnLinkType (NULL, AsnFind ("GBSet"));
  xtra.atp = AsnLinkType (NULL, AsnFind ("GBSet.E"));
  if (atp == NULL || xtra.atp == NULL) {
    Message (MSG_POSTERR, "AsnLinkType or AsnFind failed");
    return 1;
  }
  extra = &xtra;
  MemSet ((Pointer) &gbst, 0, sizeof (GBSet));
  AsnOpenStruct (aip, atp, (Pointer) &gbst);

  if (dfp != NULL) {
    DoQuery (fp, dfp, extra, get_var, do_nuc, do_prot);
  } else {
    str = ReadALine (line, sizeof (line), fp);
    while (str != NULL) {
      if (! StringHasNoText (str)) {
        ProcessAccession (str, extra, only_new, get_var, do_nuc, do_prot);
      }
      str = ReadALine (line, sizeof (line), fp);
    }
  }

  AsnCloseStruct (aip, atp, NULL);
  AsnPrintNewLine (aip);
  AsnIoClose (aip);

  FileClose (dfp);
  FileClose (fp);

  PubSeqFetchDisable ();

  return 0;
}
示例#12
0
文件: forage.cpp 项目: quido/Server
void Client::GoFish()
{
	Save(); //More desync testing
	//TODO: generate a message if we're already fishing
	/*if (!fishing_timer.Check()) {	//this isn't the right check, may need to add something to the Client class like 'bool is_fishing'
		Message_StringID(CC_Default, ALREADY_FISHING);	//You are already fishing!
		return;
	}*/

	fishing_timer.Disable();

	//we're doing this a second time (1st in Client::Handle_OP_Fishing) to make sure that, between when we started fishing & now, we're still able to fish (in case we move, change equip, etc)
	if (!CanFish())	//if we can't fish here, we don't need to bother with the rest
		return;

	//multiple entries yeilds higher probability of dropping...
	uint32 common_fish_ids[MAX_COMMON_FISH_IDS] = {
		1038, // Tattered Cloth Sandals
		1038, // Tattered Cloth Sandals
		1038, // Tattered Cloth Sandals
		13019, // Fresh Fish
		13076, // Fish Scales
		13076, // Fish Scales
		7007, // Rusty Dagger
		7007, // Rusty Dagger
		7007 // Rusty Dagger

	};

	//success formula is not researched at all

	int fishing_skill = GetSkill(SkillFishing);	//will take into account skill bonuses on pole & bait

	//make sure we still have a fishing pole on:
	int32 bslot = m_inv.HasItemByUse(ItemTypeFishingBait, 1, invWhereWorn|invWherePersonal);
	const ItemInst* Bait = nullptr;
	if (bslot != INVALID_INDEX)
		Bait = m_inv.GetItem(bslot);

	//if the bait isnt equipped, need to add its skill bonus
	if(bslot >= EmuConstants::GENERAL_BEGIN && Bait->GetItem()->SkillModType == SkillFishing) {
		fishing_skill += Bait->GetItem()->SkillModValue;
	}

	if (fishing_skill > 100)
	{
		fishing_skill = 100+((fishing_skill-100)/2);
	}

	if (MakeRandomInt(0,175) < fishing_skill) {
		uint32 food_id = 0;

		//25% chance to fish an item.
		if (MakeRandomInt(0, 399) <= fishing_skill ) {
			uint32 npc_id = 0;
			uint8 npc_chance = 0;
			food_id = database.GetZoneFishing(m_pp.zone_id, fishing_skill, npc_id, npc_chance);

			//check for add NPC
			if(npc_chance > 0 && npc_id) {
				if(npc_chance < MakeRandomInt(0, 99)) {
					const NPCType* tmp = database.GetNPCType(npc_id);
					if(tmp != nullptr) {
						NPC* npc = new NPC(tmp, nullptr, GetX()+3, GetY(), GetZ(), GetHeading(), FlyMode3);
						npc->AddLootTable();

						npc->AddToHateList(this, 1, 0, false);	//no help yelling

						entity_list.AddNPC(npc);

						Message(MT_Emote, "You fish up a little more than you bargained for...");
					}
				}
			}
		}

		//consume bait, should we always consume bait on success?
		DeleteItemInInventory(bslot, 1, true);	//do we need client update?

		if(food_id == 0) {
			int index = MakeRandomInt(0, MAX_COMMON_FISH_IDS-1);
			food_id = common_fish_ids[index];
		}

		const Item_Struct* food_item = database.GetItem(food_id);

		Message_StringID(MT_Skills, FISHING_SUCCESS);
		ItemInst* inst = database.CreateItem(food_item, 1);
		if(inst != nullptr) {
			if(CheckLoreConflict(inst->GetItem()))
			{
				Message_StringID(CC_Default, DUP_LORE);
				safe_delete(inst);
			}
			else
			{
				PushItemOnCursor(*inst);
				SendItemPacket(MainCursor, inst, ItemPacketSummonItem);

				safe_delete(inst);
				inst = m_inv.GetItem(MainCursor);
			}

			if(inst) {
				std::vector<EQEmu::Any> args;
				args.push_back(inst);
				parse->EventPlayer(EVENT_FISH_SUCCESS, this, "", inst->GetID(), &args);
			}
		}
	}
	else
	{
		//chance to use bait when you dont catch anything...
		if (MakeRandomInt(0, 4) == 1) {
			DeleteItemInInventory(bslot, 1, true);	//do we need client update?
			Message_StringID(MT_Skills, FISHING_LOST_BAIT);	//You lost your bait!
		} else {
			if (MakeRandomInt(0, 15) == 1)	//give about a 1 in 15 chance to spill your beer. we could make this a rule, but it doesn't really seem worth it
				//TODO: check for & consume an alcoholic beverage from inventory when this triggers, and set it as a rule that's disabled by default
				Message_StringID(MT_Skills, FISHING_SPILL_BEER);	//You spill your beer while bringing in your line.
			else
				Message_StringID(MT_Skills, FISHING_FAILED);	//You didn't catch anything.
		}

		parse->EventPlayer(EVENT_FISH_FAILURE, this, "", 0);
	}

	//chance to break fishing pole...
	//this is potentially exploitable in that they can fish
	//and then swap out items in primary slot... too lazy to fix right now
	if (MakeRandomInt(0, 49) == 1) {
		Message_StringID(MT_Skills, FISHING_POLE_BROKE);	//Your fishing pole broke!
		DeleteItemInInventory(MainPrimary, 0, true);
	}

	if(CheckIncreaseSkill(SkillFishing, nullptr, 5))
	{
		if(title_manager.IsNewTradeSkillTitleAvailable(SkillFishing, GetRawSkill(SkillFishing)))
			NotifyNewTitlesAvailable();
	}
}
示例#13
0
文件: ai8.cpp 项目: zarevucky/signus
int ArtificialIntelligence8 ()
{
    int i, j, k, st, id;
    TPoint p;

    Message (SigText[TXT_AI_ANALYSE]);

    // Prepocitame viditelnost
    AllowBadlife (TRUE);
    ComputeVisib ();
    RedrawMap ();
    
    LockDraw ();
    
    // Aktualizujeme specialni objekty
    Docks1 = GetField (D1X, D1Y) -> Unit;
    if (Docks1 == NO_UNIT || Units [Docks1] -> Type % BADLIFE != unDocks) 
        Docks1 = NO_UNIT;
    Docks2 = GetField (D2X, D2Y) -> Unit;
    if (Docks2 == NO_UNIT || Units [Docks2] -> Type % BADLIFE != unDocks) 
        Docks2 = NO_UNIT;
    Factory1 = GetField (F1X, F1Y) -> Unit;
    if (Factory1 == NO_UNIT || Units [Factory1] -> Type % BADLIFE != unFactory) 
        Factory1 = NO_UNIT;
    Factory2 = GetField (F2X, F2Y) -> Unit;
    if (Factory2 == NO_UNIT || Units [Factory2] -> Type % BADLIFE != unFactory) 
        Factory2 = NO_UNIT;
    Factory3 = GetField (F3X, F3Y) -> Unit;
    if (Factory3 == NO_UNIT || Units [Factory3] -> Type % BADLIFE != unFactory) 
        Factory3 = NO_UNIT;

    // Vyradime znicene jednotky z armad    
    Towers -> DeleteKilled2 (); Towers -> DeleteKilled ();
    Army1 -> DeleteKilled2 (); Army1 -> DeleteKilled ();
    Army2 -> DeleteKilled2 (); Army2 -> DeleteKilled ();
    Army3 -> DeleteKilled2 (); Army3 -> DeleteKilled ();
    AirArmy3 -> DeleteKilled2 (); AirArmy3 -> DeleteKilled ();
    Army4 -> DeleteKilled2 (); Army4 -> DeleteKilled ();
    Army5 -> DeleteKilled2 (); Army5 -> DeleteKilled ();
    Army6 -> DeleteKilled2 (); Army6 -> DeleteKilled ();
    Army7 -> DeleteKilled2 (); Army7 -> DeleteKilled ();
    Army8 -> DeleteKilled2 (); Army8 -> DeleteKilled ();
    AirArmy8 -> DeleteKilled2 (); AirArmy8 -> DeleteKilled ();
    Marine1 -> DeleteKilled2 (); Marine1 -> DeleteKilled ();
    Marine8 -> DeleteKilled2 (); Marine8 -> DeleteKilled ();
    DUPos = 0;
    
    // Testneme konec hry   
    st = AssignResult ();
    if (st != 0) {
        UnlockDraw ();  
        AllowBadlife (FALSE);       
        return st;  
    }

    // Zpracujeme seznam poli, na ktere se utocilo
    Army1 -> DoAttackedFields ();
    Army2 -> DoAttackedFields ();
    Army3 -> DoAttackedFields ();
    AirArmy3 -> DoAttackedFields ();
    Army4 -> DoAttackedFields ();
    Army5 -> DoAttackedFields ();
    Army6 -> DoAttackedFields ();
    Army7 -> DoAttackedFields ();
    Army8 -> DoAttackedFields ();
    AirArmy8 -> DoAttackedFields ();
    Marine1 -> DoAttackedFields ();
    Marine8 -> DoAttackedFields ();
    AttackFieldPos = 0;
    
    AnalyseLandscape ();    
    
    Message (SigText[TXT_AI_ARMY]);



//////////////////////////////// AKTIVACE ARMAD

    // Test zaktivovani armady 1
    if (Army1 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Army1 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army1 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani armady 2
    if (Army2 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Army2 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army2 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani armady 3
    if (Army3 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Army3 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army3 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani armady 4
    if (Army4 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Army4 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army4 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani armady 5
    if (Army5 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Army5 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army5 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani armady 6
    if (Army6 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Army6 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army6 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani armady 7
    if (Army7 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Army7 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army7 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani armady 8
    if (Army8 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Army8 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army8 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani marine 1
    if (Marine1 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Marine1 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Marine1 -> Status = asActive;
            }
        }
    }
    // Test zaktivovani marine 8
    if (Marine8 -> Status == asSleeping) {
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;
            if (Marine8 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Marine8 -> Status = asActive;
            }
        }
    }
    

///////////////////////////// AKCE ARMAD

    // Nastavime ProgressBar
    st = 0;
    st += Towers -> nofBadLife;
    if (Army1 -> Status == asActive || Army1 -> Status == asSuicide) st += Army1 -> nofBadLife;
    if (Army2 -> Status == asActive || Army2 -> Status == asSuicide) st += Army2 -> nofBadLife;
    if (Army3 -> Status == asActive || Army3 -> Status == asSuicide) st += Army3 -> nofBadLife;
    if (AirArmy3 -> Status == asActive || AirArmy3 -> Status == asSuicide) st += AirArmy3 -> nofBadLife;
    if (Army4 -> Status == asActive || Army4 -> Status == asSuicide) st += Army4 -> nofBadLife;
    if (Army5 -> Status == asActive || Army5 -> Status == asSuicide) st += Army5 -> nofBadLife;
    if (Army6 -> Status == asActive || Army6 -> Status == asSuicide) st += Army6 -> nofBadLife;
    if (Army7 -> Status == asActive || Army7 -> Status == asSuicide) st += Army7 -> nofBadLife;
    if (Army8 -> Status == asActive || Army8 -> Status == asSuicide) st += Army8 -> nofBadLife;
    if (AirArmy8 -> Status == asActive || AirArmy8 -> Status == asSuicide) st += AirArmy8 -> nofBadLife;
    if (Marine1 -> Status == asActive || Marine1 -> Status == asSuicide) st += Marine1 -> nofBadLife;
    if (Marine8 -> Status == asActive || Marine8 -> Status == asSuicide) st += Marine8 -> nofBadLife;
    if (st == 0) st = 5; // Magic number
    ProgressNull ();
    ProgressLimit (st);     

    // Vylozime letiste
    UnlockDraw ();
    for (i = BADLIFE; i < UNITS_TOP; i++){
        // Airport
        if (Units [i] != NULL && Units [i] -> Type - BADLIFE == unAirport) {            
            for (j = 0; j < ((TAirport *) Units [i]) -> LoadedUnits; j++) {
                id = ((TAirport *)Units [i]) -> Inventory [j];
                if (Units [id] -> AI_Info.State == aistFuel) {
                    st = ((TAirport *)Units [i]) -> UnloadUnit ((TUnit *)Units [id]);
                    if (st == 1) {
                        j--;
                        Units [id] -> AI_Info.State = aistNought;
                        for (k = 120; k > 1; k--) {
                            p = CartezianSnail (k);
                            p.x += Units [id] -> X; p.y += Units [id] -> Y;
                            if (p.x >= 0 && p.x < MapSizeX && p.y >= 0 && p.y < MapSizeY
                            && GetAircraftAt (p.x, p.y) == NULL) {
                                Units [id] -> Select ();
                                st = Units [id] -> MoveFar (p.x, p.y);
                                if (st == 1) break;
                                
                            }
                        }
                    }
                }
            }
        }
        // Heliport
        if (Units [i] != NULL && Units [i] -> Type - BADLIFE == unHeliport) {           
            for (j = 0; j < ((THeliport *) Units [i]) -> LoadedUnits; j++) {
                id = ((THeliport *)Units [i]) -> Inventory [j];
                if (Units [id] -> AI_Info.State == aistFuel) {
                    st = ((THeliport *)Units [i]) -> UnloadUnit ((TUnit *)Units [id]);
                    if (st == 1) {
                        j--;
                        Units [id] -> AI_Info.State = aistNought;
                        for (k = 120; k > 1; k--) {
                            p = CartezianSnail (k);
                            p.x += Units [id] -> X; p.y += Units [id] -> Y;
                            if (p.x >= 0 && p.x < MapSizeX && p.y >= 0 && p.y < MapSizeY
                            && GetAircraftAt (p.x, p.y) == NULL) {
                                Units [id] -> Select ();
                                st = Units [id] -> MoveFar (p.x, p.y);
                                if (st == 1) break;
                            }
                        }
                    }
                }
            }
        }
        // Laguna
        if (Units [i] != NULL && Units [i] -> Type - BADLIFE == unLaguna) {         
            for (j = 0; j < ((TLaguna *) Units [i]) -> LoadedUnits; j++) {
                id = ((TLaguna *)Units [i]) -> Inventory [j];
                if (Units [id] -> AI_Info.State == aistFuel) {
                    st = ((TLaguna *)Units [i]) -> UnloadUnit ((TUnit *)Units [id]);
                    if (st == 1) {
                        j--;
                        Units [id] -> AI_Info.State = aistNought;
                        for (k = 120; k > 1; k--) {
                            p = CartezianSnail (k);
                            p.x += Units [id] -> X; p.y += Units [id] -> Y;
                            if (p.x >= 0 && p.x < MapSizeX && p.y >= 0 && p.y < MapSizeY
                            && GetAircraftAt (p.x, p.y) == NULL) {
                                Units [id] -> Select ();
                                st = Units [id] -> MoveFar (p.x, p.y);
                                if (st == 1) break;
                            }
                        }
                    }
                }
            }
        }
        
    }
    LockDraw ();

    // Veze
    if (Towers -> MakeTurn () == FALSE) {
        st = AssignResult ();
        if (st != 0) {
            UnlockDraw ();  
            AllowBadlife (FALSE);       
            return st;  
        }
    }

    
    // ARMY 1
    if (Army1 -> Status == asActive || Army1 -> Status == asSuicide) {
        Army1 -> DeleteKilled ();
        
        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Army1 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army1 -> Insert (i);
            }
        }

        // Pokyn k sebevrazde       
        Army1 -> CountDangerous ();
        if (Army1 -> Dangerous <= CSuicide1) {
            Army1 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Army1 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }

        // Likvidace armady 1
        Army1 -> CountDangerous ();     
        if (Army1 -> Dangerous <= CMinDang1) {
            Army1 -> Status = asDestroyed;          
        }
        
        
    }
    
    // ARMY 2
    if (Army2 -> Status == asActive || Army2 -> Status == asSuicide) {
        Army2 -> DeleteKilled ();
        
        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Army2 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army2 -> Insert (i);
            }
        }

        // Pokyn k sebevrazde       
        Army2 -> CountDangerous ();
        if (Army2 -> Dangerous <= CSuicide2) {
            Army2 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Army2 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }

        // Likvidace armady 2
        if (Army2 -> Dangerous <= CMinDang2) {
            Army2 -> Status = asDestroyed;
        }
        
    }

    // ARMY 3
    if (Army3 -> Status == asActive || Army3 -> Status == asSuicide) {
        Army3 -> DeleteKilled ();
        
        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Army3 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army3 -> Insert (i);
            }
        }

        // Pokyn k sebevrazde       
        Army3 -> CountDangerous ();
        if (Army3 -> Dangerous <= CSuicide3) {
            Army3 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Army3 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 3
        if (Army3 -> Dangerous <= CMinDang3) {
            Army3 -> Status = asDestroyed;
        }
                
    }
    // AIR ARMY 3
    if (AirArmy3 -> Status == asActive || AirArmy3 -> Status == asSuicide) {
        AirArmy3 -> DeleteKilled ();
        
        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (AirArmy3 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                AirArmy3 -> Insert (i);
            }
        }

        // Pokyn k sebevrazde       
        AirArmy3 -> CountDangerous ();
        if (AirArmy3 -> Dangerous <= CSuicideA3) {
            AirArmy3 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (AirArmy3 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 3
        if (AirArmy3 -> Dangerous <= CMinDangA3) {
            AirArmy3 -> Status = asDestroyed;
        }
                
    }


                    
    // ARMY 4
    if (Army4 -> Status == asActive || Army4 -> Status == asSuicide) {
        Army4 -> DeleteKilled ();

        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Army4 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army4 -> Insert (i);
            }
        }
        
        // Pokyn k sebevrazde       
        Army4 -> CountDangerous ();
        if (Army4 -> Dangerous <= CSuicide4) {
            Army4 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Army4 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 4
        if (Army4 -> Dangerous <= CMinDang4) {
            Army4 -> Status = asDestroyed;
        }               
    }
    

    // ARMY 5
    if (Army5 -> Status == asActive || Army5 -> Status == asSuicide) {
        Army5 -> DeleteKilled ();

        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Army5 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army5 -> Insert (i);
            }
        }
        
        // Pokyn k sebevrazde       
        Army5 -> CountDangerous ();
        if (Army5 -> Dangerous <= CSuicide5) {
            Army5 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Army5 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 5
        if (Army5 -> Dangerous <= CMinDang5) {
            Army5 -> Status = asDestroyed;
        }               
    }


    // ARMY 6
    if (Army6 -> Status == asActive || Army6 -> Status == asSuicide) {
        Army6 -> DeleteKilled ();

        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Army6 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army6 -> Insert (i);
            }
        }
        
        // Pokyn k sebevrazde       
        Army6 -> CountDangerous ();
        if (Army6 -> Dangerous <= CSuicide6) {
            Army6 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Army6 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 6
        if (Army6 -> Dangerous <= CMinDang6) {
            Army6 -> Status = asDestroyed;
        }               
    }

    // ARMY 7
    if (Army7 -> Status == asActive || Army7 -> Status == asSuicide) {
        Army7 -> DeleteKilled ();

        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Army7 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army7 -> Insert (i);
            }
        }
        
        // Pokyn k sebevrazde       
        Army7 -> CountDangerous ();
        if (Army7 -> Dangerous <= CSuicide7) {
            Army7 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Army7 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 7
        if (Army7 -> Dangerous <= CMinDang7) {
            Army7 -> Status = asDestroyed;
        }               
    }

    // ARMY 8
    if (Army8 -> Status == asActive || Army8 -> Status == asSuicide) {
        Army8 -> DeleteKilled ();

        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Army8 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Army8 -> Insert (i);
            }
        }
        
        // Pokyn k sebevrazde       
        Army8 -> CountDangerous ();
        if (Army8 -> Dangerous <= CSuicide8) {
            Army8 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Army8 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 6
        if (Army8 -> Dangerous <= CMinDang8) {
            Army8 -> Status = asDestroyed;
        }               
    }

    // AIR ARMY 8
    if (AirArmy8 -> Status == asActive || AirArmy8 -> Status == asSuicide) {
        AirArmy8 -> DeleteKilled ();

        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (AirArmy8 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                AirArmy8 -> Insert (i);
            }
        }
        
        // Pokyn k sebevrazde       
        AirArmy8 -> CountDangerous ();
        if (AirArmy8 -> Dangerous <= CSuicideA8) {
            AirArmy8 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (AirArmy8 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 6
        if (AirArmy8 -> Dangerous <= CMinDangA8) {
            AirArmy8 -> Status = asDestroyed;
        }               
    }

    // MARINE 1
    if (Marine1 -> Status == asActive || Marine1 -> Status == asSuicide) {
        Marine1 -> DeleteKilled ();

        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Marine1 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Marine1 -> Insert (i);
            }
        }
        
        // Pokyn k sebevrazde       
        Marine1 -> CountDangerous ();
        if (Marine1 -> Dangerous <= CSuicideM1) {
            Marine1 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Marine1 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 1
        if (Marine1 -> Dangerous <= CMinDangM1) {
            Marine1 -> Status = asDestroyed;
        }               
    }

    // MARINE 8
    if (Marine8 -> Status == asActive || Marine8 -> Status == asSuicide) {
        Marine8 -> DeleteKilled ();

        // Zarazeni novych nepratel (GL)
        for (i = 0; i < BADLIFE; i++) {
            if (Units [i] == NULL) continue;            
            if (Marine8 -> IsInVisualRange (Units [i] -> X, Units [i] -> Y)) {
                Marine8 -> Insert (i);
            }
        }
        
        // Pokyn k sebevrazde       
        Marine8 -> CountDangerous ();
        if (Marine8 -> Dangerous <= CSuicideM8) {
            Marine8 -> Status = asSuicide;
        }       
        
        // Provedeme akce
        if (Marine8 -> MakeTurn () == FALSE) {
            st = AssignResult ();
            if (st != 0) {
                UnlockDraw ();  
                AllowBadlife (FALSE);       
                return st;  
            }
        }
        
        // Likvidace armady 8
        if (Marine8 -> Dangerous <= CMinDangM8) {
            Marine8 -> Status = asDestroyed;
        }               
    }



    AttackFieldPos = 0;
    
    UnlockDraw ();  
    AllowBadlife (FALSE);
    return AssignResult ();

    
}
示例#14
0
int Manager::ProcessKey(DWORD Key)
{
	int ret=FALSE;

	if (CurrentFrame)
	{
		DWORD KeyM=(Key&(~KEY_CTRLMASK));

		if (!((KeyM >= KEY_MACRO_BASE && KeyM <= KEY_MACRO_ENDBASE) || (KeyM >= KEY_OP_BASE && KeyM <= KEY_OP_ENDBASE))) // пропустим макро-коды
		{
			switch (CurrentFrame->GetType())
			{
				case MODALTYPE_PANELS:
				{
					_ALGO(CleverSysLog clv(L"Manager::ProcessKey()"));
					_ALGO(SysLog(L"Key=%s",_FARKEY_ToName(Key)));
#ifndef NO_WRAPPER
					if (CtrlObject->Cp()->ActivePanel->GetMode() == PLUGIN_PANEL)
					{
						PluginHandle *ph=(PluginHandle*)CtrlObject->Cp()->ActivePanel->GetPluginHandle();
						if (ph && ph->pPlugin->IsOemPlugin())
							if (CtrlObject->Cp()->ActivePanel->SendKeyToPlugin(Key,TRUE))
								return TRUE;
					}
#endif // NO_WRAPPER
					break;
				}
			#if 0
				case MODALTYPE_VIEWER:
					//if(((FileViewer*)CurrentFrame)->ProcessViewerInput(FrameManager->GetLastInputRecord()))
					//  return TRUE;
					break;
				case MODALTYPE_EDITOR:
					//if(((FileEditor*)CurrentFrame)->ProcessEditorInput(FrameManager->GetLastInputRecord()))
					//  return TRUE;
					break;
				case MODALTYPE_DIALOG:
					//((Dialog*)CurrentFrame)->CallDlgProc(DN_KEY,((Dialog*)CurrentFrame)->GetDlgFocusPos(),Key);
					break;
				case MODALTYPE_VMENU:
				case MODALTYPE_HELP:
				case MODALTYPE_COMBOBOX:
				case MODALTYPE_USER:
				case MODALTYPE_FINDFOLDER:
				default:
					break;
			#endif
			}
		}

#if defined(FAR_ALPHA_VERSION)

// сей код для проверки исключатор, просьба не трогать :-)
		if (Key == KEY_CTRLALTAPPS || Key == KEY_RCTRLRALTAPPS || Key == KEY_CTRLRALTAPPS || Key == KEY_RCTRLALTAPPS)
		{
			struct __ECODE
			{
				NTSTATUS Code;
				const wchar_t *Name;
			} ECode[]=
			{
				{EXCEPTION_ACCESS_VIOLATION,L"Access Violation (Read)"},
				{EXCEPTION_ACCESS_VIOLATION,L"Access Violation (Write)"},
				{EXCEPTION_INT_DIVIDE_BY_ZERO,L"Divide by zero"},
				{EXCEPTION_ILLEGAL_INSTRUCTION,L"Illegal instruction"},
				{EXCEPTION_STACK_OVERFLOW,L"Stack Overflow"},
				{EXCEPTION_FLT_DIVIDE_BY_ZERO,L"Floating-point divide by zero"},
				{EXCEPTION_BREAKPOINT,L"Breakpoint"},
#ifdef _M_IA64
				{EXCEPTION_DATATYPE_MISALIGNMENT,L"Alignment fault (IA64 specific)",},
#endif
				/*
				        {EXCEPTION_FLT_OVERFLOW,"EXCEPTION_FLT_OVERFLOW"},
				        {EXCEPTION_SINGLE_STEP,"EXCEPTION_SINGLE_STEP",},
				        {EXCEPTION_ARRAY_BOUNDS_EXCEEDED,"EXCEPTION_ARRAY_BOUNDS_EXCEEDED",},
				        {EXCEPTION_FLT_DENORMAL_OPERAND,"EXCEPTION_FLT_DENORMAL_OPERAND",},
				        {EXCEPTION_FLT_INEXACT_RESULT,"EXCEPTION_FLT_INEXACT_RESULT",},
				        {EXCEPTION_FLT_INVALID_OPERATION,"EXCEPTION_FLT_INVALID_OPERATION",},
				        {EXCEPTION_FLT_STACK_CHECK,"EXCEPTION_FLT_STACK_CHECK",},
				        {EXCEPTION_FLT_UNDERFLOW,"EXCEPTION_FLT_UNDERFLOW",},
				        {EXCEPTION_INT_OVERFLOW,"EXCEPTION_INT_OVERFLOW",0},
				        {EXCEPTION_PRIV_INSTRUCTION,"EXCEPTION_PRIV_INSTRUCTION",0},
				        {EXCEPTION_IN_PAGE_ERROR,"EXCEPTION_IN_PAGE_ERROR",0},
				        {EXCEPTION_NONCONTINUABLE_EXCEPTION,"EXCEPTION_NONCONTINUABLE_EXCEPTION",0},
				        {EXCEPTION_INVALID_DISPOSITION,"EXCEPTION_INVALID_DISPOSITION",0},
				        {EXCEPTION_GUARD_PAGE,"EXCEPTION_GUARD_PAGE",0},
				        {EXCEPTION_INVALID_HANDLE,"EXCEPTION_INVALID_HANDLE",0},
				*/
			};
			static union
			{
				int     i;
				int     *iptr;
				double  d;
			} zero_const; //, refers;
			zero_const.i=0L;
			MenuItemEx ModalMenuItem;
			ModalMenuItem.Clear();
			VMenu2 ModalMenu(L"Test Exceptions",nullptr,0,ScrY-4);
			ModalMenu.SetFlags(VMENU_WRAPMODE);
			ModalMenu.SetPosition(-1,-1,0,0);

			for (size_t I=0; I<ARRAYSIZE(ECode); I++)
			{
				ModalMenuItem.strName = ECode[I].Name;
				ModalMenu.AddItem(&ModalMenuItem);
			}

			int ExitCode=ModalMenu.Run();

			switch (ExitCode)
			{
				case -1:
					return TRUE;
				case 0:
					zero_const.i=*zero_const.iptr;
					break;
				case 1:
					*zero_const.iptr = 0;
					break;
				case 2:
					zero_const.i=1/zero_const.i;
					break;
				case 3:
#if defined(_MSC_VER)
#ifdef _M_IA64
#define __REG_IA64_IntR0 1024
					__setReg(__REG_IA64_IntR0, 666);
#else
					__ud2();
#endif
#elif defined(__GNUC__)
					asm("ud2");
#else
#error "Unsupported compiler"
#endif
					break;
				case 4:
					Test_EXCEPTION_STACK_OVERFLOW(nullptr);
					break;
				case 5:
					//refers.d = 1.0/zero_const.d;
					break;
				case 6:
					DebugBreak();
					break;
#ifdef _M_IA64
				case 7:
				{
					BYTE temp[10]={};
					double* val;
					val = (double*)(&temp[3]);
					printf("%lf\n", *val);
				}
#endif
			}

			Message(MSG_WARNING, 1, L"Test Exceptions failed", L"", ECode[ExitCode].Name, L"", MSG(MOk));
			return TRUE;
		}

#endif
		/*** БЛОК ПРИВЕЛЕГИРОВАННЫХ КЛАВИШ ! ***/

		/***   КОТОРЫЕ НЕЛЬЗЯ НАМАКРОСИТЬ    ***/
		switch (Key)
		{
			case KEY_ALT|KEY_NUMPAD0:
			case KEY_RALT|KEY_NUMPAD0:
			case KEY_ALTINS:
			case KEY_RALTINS:
			{
				RunGraber();
				return TRUE;
			}
			case KEY_CONSOLE_BUFFER_RESIZE:
				Sleep(1);
				ResizeAllFrame();
				return TRUE;
		}

		/*** А вот здесь - все остальное! ***/
		if (!Global->IsProcessAssignMacroKey)
			// в любом случае если кому-то не нужны все клавиши или
		{
			bool scrollable = false;
			if ( Global->Opt->WindowMode )
			{
				int frame_type = CurrentFrame->GetType();
				scrollable = frame_type != MODALTYPE_EDITOR && frame_type != MODALTYPE_VIEWER;
			};

			switch (Key)
			{
				// <Удалить после появления макрофункции Scroll>
				case KEY_CTRLALTUP:
				case KEY_RCTRLRALTUP:
				case KEY_CTRLRALTUP:
				case KEY_RCTRLALTUP:
					if(scrollable)
					{
						Global->Console->ScrollWindow(-1);
						return TRUE;
					}
					break;

				case KEY_CTRLALTDOWN:
				case KEY_RCTRLRALTDOWN:
				case KEY_CTRLRALTDOWN:
				case KEY_RCTRLALTDOWN:
					if(scrollable)
					{
						Global->Console->ScrollWindow(1);
						return TRUE;
					}
					break;

				case KEY_CTRLALTPGUP:
				case KEY_RCTRLRALTPGUP:
				case KEY_CTRLRALTPGUP:
				case KEY_RCTRLALTPGUP:
					if(scrollable)
					{
						Global->Console->ScrollWindow(-ScrY);
						return TRUE;
					}
					break;

				case KEY_CTRLALTHOME:
				case KEY_RCTRLRALTHOME:
				case KEY_CTRLRALTHOME:
				case KEY_RCTRLALTHOME:
					if(scrollable)
					{
						while(Global->Console->ScrollWindow(-ScrY));
						return TRUE;
					}
					break;

				case KEY_CTRLALTPGDN:
				case KEY_RCTRLRALTPGDN:
				case KEY_CTRLRALTPGDN:
				case KEY_RCTRLALTPGDN:
					if(scrollable)
					{
						Global->Console->ScrollWindow(ScrY);
						return TRUE;
					}
					break;

				case KEY_CTRLALTEND:
				case KEY_RCTRLRALTEND:
				case KEY_CTRLRALTEND:
				case KEY_RCTRLALTEND:
					if(scrollable)
					{
						while(Global->Console->ScrollWindow(ScrY));
						return TRUE;
					}
					break;
				// </Удалить после появления макрофункции Scroll>

				case KEY_CTRLW:
				case KEY_RCTRLW:
					ShowProcessList();
					return TRUE;
				case KEY_F11:
					PluginsMenu();
					FrameManager->RefreshFrame();
					//_MANAGER(SysLog(-1));
					return TRUE;
				case KEY_ALTF9:
				case KEY_RALTF9:
				{
					//_MANAGER(SysLog(1,"Manager::ProcessKey, KEY_ALTF9 pressed..."));
					Sleep(1);
					SetVideoMode();
					Sleep(1);

					/* В процессе исполнения Alt-F9 (в нормальном режиме) в очередь
					   консоли попадает WINDOW_BUFFER_SIZE_EVENT, формируется в
					   ChangeVideoMode().
					   В режиме исполнения макросов ЭТО не происходит по вполне понятным
					   причинам.
					*/
					if (CtrlObject->Macro.IsExecuting())
					{
						int PScrX=ScrX;
						int PScrY=ScrY;
						Sleep(1);
						GetVideoMode(CurSize);

						if (PScrX+1 == CurSize.X && PScrY+1 == CurSize.Y)
						{
							//_MANAGER(SysLog(-1,"GetInputRecord(WINDOW_BUFFER_SIZE_EVENT); return KEY_NONE"));
							return TRUE;
						}
						else
						{
							PrevScrX=PScrX;
							PrevScrY=PScrY;
							//_MANAGER(SysLog(-1,"GetInputRecord(WINDOW_BUFFER_SIZE_EVENT); return KEY_CONSOLE_BUFFER_RESIZE"));
							Sleep(1);
							return ProcessKey(KEY_CONSOLE_BUFFER_RESIZE);
						}
					}

					//_MANAGER(SysLog(-1));
					return TRUE;
				}
				case KEY_F12:
				{
					int TypeFrame=FrameManager->GetCurrentFrame()->GetType();

					if (TypeFrame != MODALTYPE_HELP && TypeFrame != MODALTYPE_DIALOG)
					{
						DeactivateFrame(FrameMenu(),0);
						//_MANAGER(SysLog(-1));
						return TRUE;
					}

					break; // отдадим F12 дальше по цепочке
				}

				case KEY_CTRLALTSHIFTPRESS:
				case KEY_RCTRLALTSHIFTPRESS:
				{
					if (!(Global->Opt->CASRule&1) && Key == KEY_CTRLALTSHIFTPRESS)
						break;

					if (!(Global->Opt->CASRule&2) && Key == KEY_RCTRLALTSHIFTPRESS)
						break;

					if (!Global->Opt->OnlyEditorViewerUsed)
					{
						if (CurrentFrame->FastHide())
						{
							int isPanelFocus=CurrentFrame->GetType() == MODALTYPE_PANELS;

							if (isPanelFocus)
							{
								int LeftVisible=CtrlObject->Cp()->LeftPanel->IsVisible();
								int RightVisible=CtrlObject->Cp()->RightPanel->IsVisible();
								int CmdLineVisible=CtrlObject->CmdLine->IsVisible();
								int KeyBarVisible=CtrlObject->Cp()->MainKeyBar.IsVisible();
								CtrlObject->CmdLine->ShowBackground();
								CtrlObject->Cp()->LeftPanel->Hide0();
								CtrlObject->Cp()->RightPanel->Hide0();

								switch (Global->Opt->PanelCtrlAltShiftRule)
								{
									case 0:
										CtrlObject->CmdLine->Show();
										CtrlObject->Cp()->MainKeyBar.Show();
										break;
									case 1:
										CtrlObject->Cp()->MainKeyBar.Show();
										break;
								}

								WaitKey(Key==KEY_CTRLALTSHIFTPRESS?KEY_CTRLALTSHIFTRELEASE:KEY_RCTRLALTSHIFTRELEASE);

								if (LeftVisible)      CtrlObject->Cp()->LeftPanel->Show();

								if (RightVisible)     CtrlObject->Cp()->RightPanel->Show();

								if (CmdLineVisible)   CtrlObject->CmdLine->Show();

								if (KeyBarVisible)    CtrlObject->Cp()->MainKeyBar.Show();
							}
							else
							{
								ImmediateHide();
								WaitKey(Key==KEY_CTRLALTSHIFTPRESS?KEY_CTRLALTSHIFTRELEASE:KEY_RCTRLALTSHIFTRELEASE);
							}

							FrameManager->RefreshFrame();
						}

						return TRUE;
					}

					break;
				}
				case KEY_CTRLTAB:
				case KEY_RCTRLTAB:
				case KEY_CTRLSHIFTTAB:
				case KEY_RCTRLSHIFTTAB:

					if (CurrentFrame->GetCanLoseFocus())
					{
						DeactivateFrame(CurrentFrame,(Key==KEY_CTRLTAB||Key==KEY_RCTRLTAB)?1:-1);
					}

					_MANAGER(SysLog(-1));
					return TRUE;
			}
		}

		CurrentFrame->UpdateKeyBar();
		CurrentFrame->ProcessKey(Key);
	}

	_MANAGER(SysLog(-1));
	return ret;
}
示例#15
0
文件: vendor.c 项目: jpmatsci/pcb
int
ActionLoadVendorFrom (int argc, char **argv, Coord x, Coord y)
{
  int i;
  char *fname = NULL;
  static char *default_file = NULL;
  char *sval;
  Resource *res, *drcres, *drlres;
  int type;
  bool free_fname = false;

  cached_drill = -1;

  fname = argc ? argv[0] : 0;

  if (!fname || !*fname)
    {
      fname = gui->fileselect (_("Load Vendor Resource File..."),
			       _("Picks a vendor resource file to load.\n"
				 "This file can contain drc settings for a\n"
				 "particular vendor as well as a list of\n"
				 "predefined drills which are allowed."),
			       default_file, ".res", "vendor",
			       HID_FILESELECT_READ);
      if (fname == NULL)
	AFAIL (load_vendor);

      free_fname = true;

      free (default_file);
      default_file = NULL;

      if (fname && *fname)
	default_file = strdup (fname);
    }

  /* Unload any vendor table we may have had */
  n_vendor_drills = 0;
  n_refdes = 0;
  n_value = 0;
  n_descr = 0;
  FREE (vendor_drills);
  FREE (ignore_refdes);
  FREE (ignore_value);
  FREE (ignore_descr);


  /* load the resource file */
  res = resource_parse (fname, NULL);
  if (res == NULL)
    {
      Message (_("Could not load vendor resource file \"%s\"\n"), fname);
      return 1;
    }

  /* figure out the vendor name, if specified */
  vendor_name = (char *)UNKNOWN (resource_value (res, "vendor"));

  /* figure out the units, if specified */
  sval = resource_value (res, "units");
  if (sval == NULL)
    {
      sf = MIL_TO_COORD(1);
    }
  else if ((NSTRCMP (sval, "mil") == 0) || (NSTRCMP (sval, "mils") == 0))
    {
      sf = MIL_TO_COORD(1);
    }
  else if ((NSTRCMP (sval, "inch") == 0) || (NSTRCMP (sval, "inches") == 0))
    {
      sf = INCH_TO_COORD(1);
    }
  else if (NSTRCMP (sval, "mm") == 0)
    {
      sf = MM_TO_COORD(1);
    }
  else
    {
      Message ("\"%s\" is not a supported units.  Defaulting to inch\n",
	       sval);
      sf = INCH_TO_COORD(1);
    }


  /* default to ROUND_UP */
  rounding_method = ROUND_UP;

  /* extract the drillmap resource */
  drlres = resource_subres (res, "drillmap");
  if (drlres == NULL)
    {
      Message (_("No drillmap resource found\n"));
    }
  else
    {
      sval = resource_value (drlres, "round");
      if (sval != NULL)
	{
	  if (NSTRCMP (sval, "up") == 0)
	    {
	      rounding_method = ROUND_UP;
	    }
	  else if (NSTRCMP (sval, "nearest") == 0)
	    {
	      rounding_method = CLOSEST;
	    }
	  else
	    {
	      Message (_
		       ("\"%s\" is not a valid rounding type.  Defaulting to up\n"),
		       sval);
	      rounding_method = ROUND_UP;
	    }
	}

      process_skips (resource_subres (drlres, "skips"));

      for (i = 0; i < drlres->c; i++)
	{
	  type = resource_type (drlres->v[i]);
	  switch (type)
	    {
	    case 10:
	      /* just a number */
	      add_to_drills (drlres->v[i].value);
	      break;

	    default:
	      break;
	    }
	}
    }

  /* Extract the DRC resource */
  drcres = resource_subres (res, "drc");

  sval = resource_value (drcres, "copper_space");
  if (sval != NULL)
    {
      PCB->Bloat = floor (sf * atof (sval) + 0.5);
      Message (_("Set DRC minimum copper spacing to %.2f mils\n"),
	       0.01 * PCB->Bloat);
    }

  sval = resource_value (drcres, "copper_overlap");
  if (sval != NULL)
    {
      PCB->Shrink = floor (sf * atof (sval) + 0.5);
      Message (_("Set DRC minimum copper overlap to %.2f mils\n"),
	       0.01 * PCB->Shrink);
    }

  sval = resource_value (drcres, "copper_width");
  if (sval != NULL)
    {
      PCB->minWid = floor (sf * atof (sval) + 0.5);
      Message (_("Set DRC minimum copper spacing to %.2f mils\n"),
	       0.01 * PCB->minWid);
    }

  sval = resource_value (drcres, "silk_width");
  if (sval != NULL)
    {
      PCB->minSlk = floor (sf * atof (sval) + 0.5);
      Message (_("Set DRC minimum silk width to %.2f mils\n"),
	       0.01 * PCB->minSlk);
    }

  sval = resource_value (drcres, "min_drill");
  if (sval != NULL)
    {
      PCB->minDrill = floor (sf * atof (sval) + 0.5);
      Message (_("Set DRC minimum drill diameter to %.2f mils\n"),
	       0.01 * PCB->minDrill);
    }

  sval = resource_value (drcres, "min_ring");
  if (sval != NULL)
    {
      PCB->minRing = floor (sf * atof (sval) + 0.5);
      Message (_("Set DRC minimum annular ring to %.2f mils\n"),
	       0.01 * PCB->minRing);
    }

  Message (_("Loaded %d vendor drills from %s\n"), n_vendor_drills, fname);
  Message (_("Loaded %d RefDes skips, %d Value skips, %d Descr skips\n"),
	   n_refdes, n_value, n_descr);

  vendorMapEnable = true;
  apply_vendor_map ();
  if (free_fname)
    free (fname);
  return 0;
}
示例#16
0
static void ProcessMultipleRecord (
  CharPtr filename,
  CSpeedFlagPtr cfp
)

{
  AsnIoPtr     aip;
  AsnTypePtr   atp;
  BioseqPtr    bsp;
  Char         buf [41];
  Uint2        entityID;
  FILE         *fp;
  SeqEntryPtr  fsep;
  Char         longest [41];
  Int4         numrecords, x;
  SeqEntryPtr  sep;
  time_t       starttime, stoptime, worsttime;
#ifdef OS_UNIX
  Char         cmmd [256];
  CharPtr      gzcatprog;
  int          ret;
  Boolean      usedPopen = FALSE;
#endif

  if (cfp == NULL) return;

  if (StringHasNoText (filename)) return;

#ifndef OS_UNIX
  if (cfp->compressed) {
    Message (MSG_POSTERR, "Can only decompress on-the-fly on UNIX machines");
    return;
  }
#endif

#ifdef OS_UNIX
  if (cfp->compressed) {
    gzcatprog = getenv ("NCBI_UNCOMPRESS_BINARY");
    if (gzcatprog != NULL) {
      sprintf (cmmd, "%s %s", gzcatprog, filename);
    } else {
      ret = system ("gzcat -h >/dev/null 2>&1");
      if (ret == 0) {
        sprintf (cmmd, "gzcat %s", filename);
      } else if (ret == -1) {
        Message (MSG_POSTERR, "Unable to fork or exec gzcat in ScanBioseqSetRelease");
        return;
      } else {
        ret = system ("zcat -h >/dev/null 2>&1");
        if (ret == 0) {
          sprintf (cmmd, "zcat %s", filename);
        } else if (ret == -1) {
          Message (MSG_POSTERR, "Unable to fork or exec zcat in ScanBioseqSetRelease");
          return;
        } else {
          Message (MSG_POSTERR, "Unable to find zcat or gzcat in ScanBioseqSetRelease - please edit your PATH environment variable");
          return;
        }
      }
    }
    fp = popen (cmmd, /* cfp->binary? "rb" : */ "r");
    usedPopen = TRUE;
  } else {
    fp = FileOpen (filename, cfp->binary? "rb" : "r");
  }
#else
  fp = FileOpen (filename, cfp->binary? "rb" : "r");
#endif
  if (fp == NULL) {
    Message (MSG_POSTERR, "FileOpen failed for input file '%s'", filename);
    return;
  }

  aip = AsnIoNew (cfp->binary? ASNIO_BIN_IN : ASNIO_TEXT_IN, fp, NULL, NULL, NULL);
  if (aip == NULL) {
    Message (MSG_ERROR, "AsnIoNew failed for input file '%s'", filename);
    return;
  }

  if (cfp->logfp != NULL) {
    fprintf (cfp->logfp, "%s\n\n", filename);
    fflush (cfp->logfp);
  }

  longest [0] = '\0';
  worsttime = 0;
  numrecords = 0;

  atp = cfp->atp_bss;

  while ((atp = AsnReadId (aip, cfp->amp, atp)) != NULL) {
    if (atp == cfp->atp_se) {

      sep = SeqEntryAsnRead (aip, atp);
      if (sep != NULL) {

        entityID = ObjMgrGetEntityIDForChoice (sep);

        fsep = FindNthBioseq (sep, 1);
        if (fsep != NULL && fsep->choice == 1) {
          bsp = (BioseqPtr) fsep->data.ptrvalue;
          if (bsp != NULL) {
            SeqIdWrite (bsp->id, buf, PRINTID_FASTA_LONG, sizeof (buf));
            if (cfp->logfp != NULL) {
              fprintf (cfp->logfp, "%s\n", buf);
              fflush (cfp->logfp);
            }
          }
        }

        starttime = GetSecs ();

        for (x = 0; x < cfp->maxcount; x++) {
          DoProcess (sep, entityID, cfp);
        }
        stoptime = GetSecs ();

        if (stoptime - starttime > worsttime) {
          worsttime = stoptime - starttime;
          StringCpy (longest, buf);
        }
        numrecords++;

        ObjMgrFreeByEntityID (entityID);
      }

    } else {

      AsnReadVal (aip, atp, NULL);
    }
  }

  AsnIoFree (aip, FALSE);

#ifdef OS_UNIX
  if (usedPopen) {
    pclose (fp);
  } else {
    FileClose (fp);
  }
#else
  FileClose (fp);
#endif
  if (cfp->logfp != NULL && (! StringHasNoText (longest))) {
    fprintf (cfp->logfp, "Longest processing time %ld seconds on %s\n",
             (long) worsttime, longest);
    fprintf (cfp->logfp, "Total number of records %ld\n", (long) numrecords);
    fflush (cfp->logfp);
  }
}
示例#17
0
文件: vendor.c 项目: jpmatsci/pcb
static void
apply_vendor_map (void)
{
  int i;
  int changed, tot;
  bool state;

  state = vendorMapEnable;

  /* enable mapping */
  vendorMapEnable = true;

  /* reset our counts */
  changed = 0;
  tot = 0;

  /* If we have loaded vendor drills, then apply them to the design */
  if (n_vendor_drills > 0)
    {

      /* first all the vias */
      VIA_LOOP (PCB->Data);
      {
	tot++;
	if (via->DrillingHole != vendorDrillMap (via->DrillingHole))
	  {
	    /* only change unlocked vias */
	    if (!TEST_FLAG (LOCKFLAG, via))
	      {
		if (ChangeObject2ndSize (VIA_TYPE, via, NULL, NULL,
					 vendorDrillMap (via->DrillingHole),
					 true, false))
		  changed++;
		else
		  {
		    Message (_
			     ("Via at %.2f, %.2f not changed.  Possible reasons:\n"
			      "\t- pad size too small\n"
			      "\t- new size would be too large or too small\n"),
			     0.01 * via->X, 0.01 * via->Y);
		  }
	      }
	    else
	      {
		Message (_("Locked via at %.2f, %.2f not changed.\n"),
			 0.01 * via->X, 0.01 * via->Y);
	      }
	  }
      }
      END_LOOP;

      /* and now the pins */
      ELEMENT_LOOP (PCB->Data);
      {
	/*
	 * first figure out if this element should be skipped for some
	 * reason
	 */
	if (vendorIsElementMappable (element))
	  {
	    /* the element is ok to modify, so iterate over its pins */
	    PIN_LOOP (element);
	    {
	      tot++;
	      if (pin->DrillingHole != vendorDrillMap (pin->DrillingHole))
		{
		  if (!TEST_FLAG (LOCKFLAG, pin))
		    {
		      if (ChangeObject2ndSize (PIN_TYPE, element, pin, NULL,
					       vendorDrillMap (pin->
							       DrillingHole),
					       true, false))
			changed++;
		      else
			{
			  Message (_
				   ("Pin %s (%s) at %.2f, %.2f (element %s, %s, %s) not changed.\n"
				    "\tPossible reasons:\n"
				    "\t- pad size too small\n"
				    "\t- new size would be too large or too small\n"),
				   UNKNOWN (pin->Number), UNKNOWN (pin->Name),
				   0.01 * pin->X, 0.01 * pin->Y,
				   UNKNOWN (NAMEONPCB_NAME (element)),
				   UNKNOWN (VALUE_NAME (element)),
				   UNKNOWN (DESCRIPTION_NAME (element)));
			}
		    }
		  else
		    {
		      Message (_
			       ("Locked pin at %-6.2f, %-6.2f not changed.\n"),
			       0.01 * pin->X, 0.01 * pin->Y);
		    }
		}
	    }
	    END_LOOP;
	  }
      }
      END_LOOP;

      Message (_("Updated %d drill sizes out of %d total\n"), changed, tot);

      /* Update the current Via */
      if (Settings.ViaDrillingHole !=
	  vendorDrillMap (Settings.ViaDrillingHole))
	{
	  changed++;
	  Settings.ViaDrillingHole =
	    vendorDrillMap (Settings.ViaDrillingHole);
	  Message (_("Adjusted active via hole size to be %6.2f mils\n"),
		   0.01 * Settings.ViaDrillingHole);
	}

      /* and update the vias for the various routing styles */
      for (i = 0; i < NUM_STYLES; i++)
	{
	  if (PCB->RouteStyle[i].Hole !=
	      vendorDrillMap (PCB->RouteStyle[i].Hole))
	    {
	      changed++;
	      PCB->RouteStyle[i].Hole =
		vendorDrillMap (PCB->RouteStyle[i].Hole);
	      Message (_
		       ("Adjusted %s routing style via hole size to be %6.2f mils\n"),
		       PCB->RouteStyle[i].Name,
		       0.01 * PCB->RouteStyle[i].Hole);
	      if (PCB->RouteStyle[i].Diameter <
		  PCB->RouteStyle[i].Hole + MIN_PINORVIACOPPER)
		{
		  PCB->RouteStyle[i].Diameter =
		    PCB->RouteStyle[i].Hole + MIN_PINORVIACOPPER;
		  Message (_
			   ("Increased %s routing style via diameter to %6.2f mils\n"),
			   PCB->RouteStyle[i].Name,
			   0.01 * PCB->RouteStyle[i].Diameter);
		}
	    }
	}

      /* 
       * if we've changed anything, indicate that we need to save the
       * file, redraw things, and make sure we can undo.
       */
      if (changed)
	{
	  SetChangedFlag (true);
	  Redraw ();
	  IncrementUndoSerialNumber ();
	}
    }

  /* restore mapping on/off */
  vendorMapEnable = state;
}
示例#18
0
//------------------------------------------------------------------------------
// Name: 
//------------------------------------------------------------------------------
IDebugEvent::Message PlatformEvent::error_description() const {
	Q_ASSERT(is_error());

	const edb::address_t fault_address = reinterpret_cast<edb::address_t>(fault_address_);

	switch(code()) {
	case SIGSEGV:
		return Message(
			tr("Illegal Access Fault"),
			tr(
				"<p>The debugged application encountered a segmentation fault.<br />The address <strong>0x%1</strong> could not be accessed.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>").arg(edb::v1::format_pointer(fault_address))
			);
	case SIGILL:
		return Message(
			tr("Illegal Instruction Fault"),
			tr(
				"<p>The debugged application attempted to execute an illegal instruction.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case SIGFPE:
		switch(fault_code_) {
		case FPE_INTDIV:
		return Message(
			tr("Divide By Zero"),
			tr(
				"<p>The debugged application tried to divide an integer value by an integer divisor of zero.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
		default:
			return Message(
				tr("Floating Point Exception"),
				tr(
					"<p>The debugged application encountered a floating-point exception.</p>"
					"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
				);
		}

	case SIGABRT:
		return Message(
			tr("Application Aborted"),
			tr(
				"<p>The debugged application has aborted.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case SIGBUS:
		return Message(
			tr("Bus Error"),
			tr(
				"<p>The debugged application tried to read or write data that is misaligned.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
#ifdef SIGSTKFLT
	case SIGSTKFLT:
		return Message(
			tr("Stack Fault"),
			tr(
				"<p>The debugged application encountered a stack fault.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
#endif
	case SIGPIPE:
		return Message(
			tr("Broken Pipe Fault"),
			tr(
				"<p>The debugged application encountered a broken pipe fault.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	default:
		return Message();
	}
}
示例#19
0
文件: vendor.c 项目: jpmatsci/pcb
/* deal with the "skip" subresource */
static void
process_skips (Resource * res)
{
  int type;
  int i, k;
  char *sval;
  int *cnt;
  char ***lst = NULL;

  if (res == NULL)
    return;

  for (i = 0; i < res->c; i++)
    {
      type = resource_type (res->v[i]);
      switch (type)
	{
	case 1:
	  /* 
	   * an unnamed sub resource.  This is something like
	   * {refdes "J3"}
	   */
	  sval = res->v[i].subres->v[0].value;
	  if (sval == NULL)
	    {
	      Message ("Error:  null skip value\n");
	    }
	  else
	    {
	      if (NSTRCMP (sval, "refdes") == 0)
		{
		  cnt = &n_refdes;
		  lst = &ignore_refdes;
		}
	      else if (NSTRCMP (sval, "value") == 0)
		{
		  cnt = &n_value;
		  lst = &ignore_value;
		}
	      else if (NSTRCMP (sval, "descr") == 0)
		{
		  cnt = &n_descr;
		  lst = &ignore_descr;
		}
	      else
		{
		  cnt = NULL;
		}

	      /* add the entry to the appropriate list */
	      if (cnt != NULL)
		{
		  for (k = 1; k < res->v[i].subres->c; k++)
		    {
		      sval = res->v[i].subres->v[k].value;
		      (*cnt)++;
		      if ((*lst =
			   (char **) realloc (*lst,
					      (*cnt) * sizeof (char *))) ==
			  NULL)
			{
			  fprintf (stderr, "realloc() failed\n");
			  exit (-1);
			}
		      (*lst)[*cnt - 1] = strdup (sval);
		    }
		}
	    }
	  break;

	default:
	  Message (_("Ignored resource type = %d in skips= section\n"), type);
	}
    }

}
示例#20
0
BOOL CALLBACK Main_DlgProc (HWND hDlg, UINT msg, WPARAM wp, LPARAM lp)
{
   static UINT msgCheckTerminate = 0;
   if (msgCheckTerminate == 0)
      msgCheckTerminate = RegisterWindowMessage (TEXT("AfsCredsCheckTerminate"));

   if (msg == msgCheckTerminate)
      {
      Main_OnCheckTerminate();
      }
   else switch (msg)
      {
      case WM_INITDIALOG:
         g.hMain = hDlg;
         Main_OnInitDialog (hDlg);
         break;

      case WM_DESTROY:
         Creds_CloseLibraries();
         ChangeTrayIcon (NIM_DELETE);
         break;

      case WM_ACTIVATEAPP:
         if (wp)
            {
            Main_RepopulateTabs (FALSE);
            }
         break;

      case WM_COMMAND:
         switch (LOWORD(wp))
            {
            case IDOK:
            case IDCANCEL:
               Main_Show (FALSE);
               break;

            case M_ACTIVATE:
               if (g.fIsWinNT || IsServiceRunning())
                  {
                  if (!lp) // Got here from "/show" parameter? switch tabs.
                     {
                     HWND hTab = GetDlgItem (g.hMain, IDC_TABS);
                     TabCtrl_SetCurSel (hTab, 0);
                     Main_OnSelectTab();
                     }
                  Main_Show (TRUE);
                  }
               else
                  {
                  Message (MB_ICONHAND, IDS_UNCONFIG_TITLE_95, IDS_UNCONFIG_DESC_95);
                  }
               break;

            case M_TERMINATE:
               if (g.fIsWinNT && IsServiceRunning())
                  ModalDialog (IDD_TERMINATE, NULL, (DLGPROC)Terminate_DlgProc);
               else if (g.fIsWinNT)
                  ModalDialog (IDD_TERMINATE_SMALL, NULL, (DLGPROC)Terminate_DlgProc);
               else // (!g.fIsWinNT)
                  ModalDialog (IDD_TERMINATE_SMALL_95, NULL, (DLGPROC)Terminate_DlgProc);
               break;

            case M_TERMINATE_NOW:
               Quit();
               break;

            case M_REMIND:
               Main_OnCheckMenuRemind();
               break;
            }
         break;

      case WM_TIMER:
         Main_OnRemindTimer();
         break;

      case WM_NOTIFY:
         switch (((NMHDR*)lp)->code)
            {
            case TCN_SELCHANGE:
               Main_OnSelectTab();
               break;
            }
         break;

      case WM_TRAYICON:
         switch (lp)
            {
            case WM_LBUTTONDOWN:
               if (IsServiceRunning() || !IsServiceConfigured())
                  Main_Show (TRUE);
               else if (!g.fIsWinNT)
                  Message (MB_ICONHAND, IDS_UNCONFIG_TITLE_95, IDS_UNCONFIG_DESC_95);
               else
                  ShowStartupWizard();
               break;

            case WM_RBUTTONDOWN:
               HMENU hm;
               if ((hm = TaLocale_LoadMenu (MENU_TRAYICON)) != 0)
                  {
                  POINT pt;
                  GetCursorPos(&pt);

                  HMENU hmDummy = CreateMenu();
                  InsertMenu (hmDummy, 0, MF_POPUP, (UINT)hm, NULL);

                  BOOL fRemind = FALSE;
                  lock_ObtainMutex(&g.credsLock);
                  for (size_t iCreds = 0; iCreds < g.cCreds; ++iCreds)
                     {
                     if (g.aCreds[ iCreds ].fRemind)
                        fRemind = TRUE;
                     }
                  lock_ReleaseMutex(&g.credsLock);
                  CheckMenuItem (hm, M_REMIND, MF_BYCOMMAND | ((fRemind) ? MF_CHECKED : MF_UNCHECKED));
		  SetForegroundWindow(hDlg);
                  TrackPopupMenu (GetSubMenu (hmDummy, 0),
                                  TPM_RIGHTALIGN | TPM_RIGHTBUTTON,
                                  pt.x, pt.y, NULL, hDlg, NULL);
		  PostMessage(hDlg, WM_NULL, 0, 0);
                  DestroyMenu (hmDummy);
                  }
               break;

            case WM_MOUSEMOVE:
               Main_OnMouseOver();
               break;
            }
         break;
      case WM_OBTAIN_TOKENS:
          if ( InterlockedIncrement (&g.fShowingMessage) != 1 )
              InterlockedDecrement (&g.fShowingMessage);
          else
              ShowObtainCreds (wp, (char *)lp);
          GlobalFree((void *)lp);
          break;

      case WM_START_SERVICE:
          {
              SC_HANDLE hManager;
              if ((hManager = OpenSCManager ( NULL, NULL, 
                                              SC_MANAGER_CONNECT |
                                              SC_MANAGER_ENUMERATE_SERVICE |
                                              SC_MANAGER_QUERY_LOCK_STATUS)) != NULL)
              {
                  SC_HANDLE hService;
                  if ((hService = OpenService ( hManager, TEXT("TransarcAFSDaemon"), 
                                                SERVICE_QUERY_STATUS | SERVICE_START)) != NULL)
                  {
                      if (StartService (hService, 0, 0))
                          TestAndDoMapShare(SERVICE_START_PENDING);
		      if ( KFW_is_available() && KFW_AFS_wait_for_service_start() ) {
#ifdef USE_MS2MIT
			  KFW_import_windows_lsa();
#endif /* USE_MS2MIT */
			  KFW_AFS_renew_tokens_for_all_cells();
		      }

                      CloseServiceHandle (hService);
                  }

                  CloseServiceHandle (hManager);
              }
              if (KFW_AFS_wait_for_service_start())
		  ObtainTokensFromUserIfNeeded(g.hMain);
          }
          break;
      }

   return FALSE;
}
示例#21
0
文件: vendor.c 项目: jpmatsci/pcb
static bool
rematch (const char *re, const char *s)
{
  /*
   * If this system has regular expression capability, then
   * add support for regular expressions in the skip lists.
   */

#if defined(HAVE_REGCOMP)

  int result;
  regmatch_t match;
  regex_t compiled;

  /* compile the regular expression */
  result = regcomp (&compiled, re, REG_EXTENDED | REG_ICASE | REG_NOSUB);
  if (result)
    {
      char errorstring[128];

      regerror (result, &compiled, errorstring, sizeof (errorstring));
      Message ("regexp error: %s\n", errorstring);
      regfree (&compiled);
      return (false);
    }

  result = regexec (&compiled, s, 1, &match, 0);
  regfree (&compiled);

  if (result == 0)
    return (true);
  else
    return (false);

#elif defined(HAVE_RE_COMP)
  int m;
  char *rslt;

  /* compile the regular expression */
  if ((rslt = re_comp (re)) != NULL)
    {
      Message ("re_comp error: %s\n", rslt);
      return (false);
    }

  m = re_exec (s);

  switch m
    {
    case 1:
      return (true);
      break;

    case 0:
      return (false);
      break;

    default:
      Message ("re_exec error\n");
      break;
    }

#else
  return (false);
#endif

}
示例#22
0
//! [sending a message]
void Window::sendMessage()
{
    thisMessage = Message(editor->toPlainText(), thisMessage.headers());
    emit messageSent(thisMessage);
}
示例#23
0
void GeneralTab_OnRefresh (HWND hDlg, BOOL fRequery)
{
   // If necessary, update any fields in g.Configuration that we care about
   //
   if (fRequery)
      {
      if (g.fIsWinNT)
         Config_GetGatewayFlag (&g.Configuration.fBeGateway);
      else
         Config_GetGatewayName (g.Configuration.szGateway);

      Config_GetCellName (g.Configuration.szCell);
      g.Configuration.fLogonAuthent=RWLogonOption(TRUE,LOGON_OPTION_INTEGRATED);
      Config_GetTrayIconFlag (&g.Configuration.fShowTrayIcon);

      if (!g.fIsWinNT)
         SetDlgItemText (hDlg, IDC_GATEWAY, g.Configuration.szGateway);
      else
         CheckDlgButton (hDlg, IDC_GATEWAY, g.Configuration.fBeGateway);

      SetDlgItemText (hDlg, IDC_CELL, g.Configuration.szCell);
      CheckDlgButton (hDlg, IDC_LOGON, g.Configuration.fLogonAuthent);
      CheckDlgButton (hDlg, IDC_TRAYICON, g.Configuration.fShowTrayIcon);
      }

   // Update our display of the service's status
   //
   DWORD CurrentState = Config_GetServiceState();
   BOOL fIfServiceStopped = !(g.fIsWinNT && !g.fIsAdmin);
   BOOL fIfServiceRunning = fIfServiceStopped && (CurrentState == SERVICE_RUNNING);

   GeneralTab_ShowCurrentState (hDlg);

   EnableWindow (GetDlgItem (hDlg, IDC_CELL), fIfServiceStopped && g.fIsWinNT);

   EnableWindow (GetDlgItem (hDlg, IDC_LOGON), fIfServiceStopped);
   EnableWindow (GetDlgItem (hDlg, IDC_GATEWAY), fIfServiceStopped);

   // Update our warning. Note that under WinNT, this tab doesn't have any
   // controls (other than Start Service) which disable just because the
   // service isn't running...so don't show that warning in that case.
   //
   TCHAR szText[ cchRESOURCE ];
   if ((!g.fIsWinNT) && (CurrentState != SERVICE_RUNNING))
      {
      GetString (szText, IDS_WARN_STOPPED);
      SetDlgItemText (hDlg, IDC_WARN, szText);
      ShowWindow (GetDlgItem (hDlg, IDC_WARN), SW_SHOW);
      }
   else if (g.fIsWinNT && !g.fIsAdmin)
      {
      GetString (szText, IDS_WARN_ADMIN);
      SetDlgItemText (hDlg, IDC_WARN, szText);
      ShowWindow (GetDlgItem (hDlg, IDC_WARN), SW_SHOW);
      }
   else // ((CurrentState == SERVICE_RUNNING) && (g.fIsAdmin))
      {
      ShowWindow (GetDlgItem (hDlg, IDC_WARN), SW_HIDE);
      }

   GeneralTab_OnGateway (hDlg);

   // If the service isn't running/stopped, we may need to complain
   //
   if ((CurrentState == SERVICE_RUNNING) && (l.fWarnIfNotStopped))
      {
      Message (MB_ICONHAND, GetErrorTitle(), IDS_SERVICE_FAIL_STOP, TEXT("%08lX"), ERROR_SERVICE_SPECIFIC_ERROR);
      }
   else if ((CurrentState == SERVICE_STOPPED) && (l.fWarnIfStopped))
      {
      Message (MB_ICONHAND, GetErrorTitle(), IDS_SERVICE_FAIL_START, TEXT("%08lX"), ERROR_SERVICE_SPECIFIC_ERROR);
      }

   if ((CurrentState == SERVICE_RUNNING) || (CurrentState == SERVICE_STOPPED))
      {
      BOOL fRestart = ((CurrentState == SERVICE_STOPPED) && (l.fRestartIfStopped));
      l.fWarnIfStopped = FALSE;
      l.fWarnIfNotStopped = FALSE;
      l.fRestartIfStopped = FALSE;
      l.fServiceIsRunning = (CurrentState == SERVICE_RUNNING);

      if (fRestart)
         {
         GeneralTab_DoStartStop (hDlg, TRUE, FALSE);
         }
      }
}
示例#24
0
void cdecl free(void * pntr)
#endif
{
USHORT usSel;
BYTE _huge * pHeapStart;
BYTE _huge * pHeapEnd;
BYTE _huge * pWork;
BYTE _huge * pToFree = pntr;
BYTE _huge * pPrev;
BYTE _huge * pNext;
USHORT rc;

   if (f32Parms.fMessageActive & LOG_MEM)
      Message("free %lX", pntr);

/*   CheckHeap();*/

   if (OFFSETOF(pntr) == 0)
      {
      freeseg(pntr);
      return;
      }


   GetMemAccess();

   for (usSel = 0; usSel < MAX_SELECTORS; usSel++)
      {
      if (SELECTOROF(pntr) == SELECTOROF(rgpSegment[usSel]))
         break;
      }
   if (usSel == MAX_SELECTORS)
      {
      CritMessage("FAT32: %lX not found in free!", pntr);
      Message("FAT32: %lX not found in free!", pntr);
      ReleaseMemAccess();
      return;
      }

   pHeapStart = rgpSegment[usSel];
   pHeapEnd = pHeapStart + HEAP_SIZE;

   rc = MY_PROBEBUF(PB_OPREAD, (PBYTE)pHeapStart, HEAP_SIZE);
   if (rc)
      {
      CritMessage("FAT32: Protection VIOLATION in free (SYS%d)", rc);
      Message("FAT32: Protection VIOLATION in free (SYS%d)", rc);
      ReleaseMemAccess();
      return;
      }

   pWork = pHeapStart;
   pPrev = NULL;
   while (pWork < pHeapEnd)
      {
      if (pWork + sizeof (ULONG) == pToFree)
         {
         if (pPrev && IsBlockFree(pPrev))
            {
            SetBlockSize(pPrev,
               BlockSize(pPrev) + BlockSize(pWork) + sizeof (ULONG));
            pWork = pPrev;
            }

         pNext = pWork + BlockSize(pWork) + sizeof (ULONG);
         if (pNext < pHeapEnd && IsBlockFree(pNext))
            SetBlockSize(pWork, BlockSize(pWork) + BlockSize(pNext) + sizeof (ULONG));

         SetFree(pWork);
         break;
         }
      else
         pPrev = pWork;

      pWork += BlockSize(pWork) + sizeof (ULONG);
      }
   if (pWork >= pHeapEnd)
      {
      CritMessage("FAT32: ERROR: Address not found in free");
      Message("ERROR: Address not found in free");
      ReleaseMemAccess();
      return;
      }

   /*
      free selector if no longer needed
   */
   if (usSel > 0 &&
      BlockSize(rgpSegment[usSel]) == (HEAP_SIZE - sizeof (ULONG)) &&
      IsBlockFree(rgpSegment[usSel]))
      {
      PBYTE p = rgpSegment[usSel];
      rgpSegment[usSel] = NULL;
      freeseg(p);
      }
   ReleaseMemAccess();
}
示例#25
0
bool Panel::MakeListFile(string& ListFileName, bool ShortNames, string_view const Modifers)
{
	uintptr_t CodePage = CP_OEMCP;

	if (!Modifers.empty())
	{
		if (contains(Modifers, L'A')) // ANSI
		{
			CodePage = CP_ACP;
		}
		else if (contains(Modifers, L'U')) // UTF8
		{
			CodePage = CP_UTF8;
		}
		else if (contains(Modifers, L'W')) // UTF16LE
		{
			CodePage = CP_UNICODE;
		}
	}

	const auto& transform = [&](string& strFileName)
	{
		if (!Modifers.empty())
		{
			if (contains(Modifers, L'F') && PointToName(strFileName).size() == strFileName.size()) // 'F' - использовать полный путь; //BUGBUG ?
			{
				strFileName = path::join(ShortNames ? ConvertNameToShort(m_CurDir) : m_CurDir, strFileName); //BUGBUG ?
			}

			if (contains(Modifers, L'Q')) // 'Q' - заключать имена с пробелами в кавычки;
				QuoteSpaceOnly(strFileName);

			if (contains(Modifers, L'S')) // 'S' - использовать '/' вместо '\' в путях файлов;
			{
				ReplaceBackslashToSlash(strFileName);
			}
		}
	};

	try
	{
		ListFileName = MakeTemp();
		if (const auto ListFile = os::fs::file(ListFileName, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS))
		{
			os::fs::filebuf StreamBuffer(ListFile, std::ios::out);
			std::ostream Stream(&StreamBuffer);
			Stream.exceptions(Stream.badbit | Stream.failbit);
			encoding::writer Writer(Stream, CodePage);

			for (const auto& i: enum_selected())
			{
				auto Name = ShortNames? i.AlternateFileName() : i.FileName;

				transform(Name);

				Writer.write(Name);
				Writer.write(L"\r\n"sv);
			}

			Stream.flush();
		}
		else
		{
			throw MAKE_FAR_EXCEPTION(msg(lng::MCannotCreateListTemp));
		}

		return true;
	}
	catch (const far_exception& e)
	{
		os::fs::delete_file(ListFileName);
		Message(MSG_WARNING, e.get_error_state(),
			msg(lng::MError),
			{
				msg(lng::MCannotCreateListFile),
				e.get_message()
			},
			{ lng::MOk });
		return false;
	}
}
//连接
bool implementsetting::Connect(void)
{
    if (!bLoadMap)
    {
        Message("SWITCH::load map failed!");
        return false;
    }

    return true;

    //bool result = true,cyc2 = false;
    //regex pattern("\\d{1,4}");
    //smatch mat;

    //for(map<string,string>::iterator hostIter = __ipmap.begin();
    //	hostIter != __ipmap.end();
    //	hostIter++)
    //{
    //	regex_search(hostIter->first, mat, pattern);

    //	string strTemp(mat[0].str());

    //	if ( strTemp != "" )
    //	{
    //		__hostCtrl[strTemp].state = __hostCtrl[strTemp].enable;
    //	}
    //	else
    //	{
    //		strTemp = hostIter->first;
    //	}

    //	if (!__hostCtrl[strTemp].enable)continue;

    //	IOConnectBegin(hostIter->second);
    //}

    //bool delayFirst = true;
    //bool funcResult = true;
    //string infoPrintf("");

    //for (map<string, stHostControl>::iterator itr = __hostCtrl.begin();
    //	itr != __hostCtrl.end();
    //	itr++)
    //{
    //	if (!itr->second.enable)continue;

    //	result = IOConnectEnd(itr->second.ip, delayFirst?3000:500);
    //
    //	if (result)
    //		LoadModuleState(itr->second.ip);
    //	else
    //		funcResult = false;

    //	if (!funcResult)
    //	{
    //		infoPrintf.append("<Switch IP - "+itr->second.ip+">:Failed!\n");

    //		string info("SWITCH::Connet::IP(");
    //		info.append(itr->second.ip);
    //		info.append(")::Failed");
    //		Message(info);
    //	}

    //	itr->second.state = result;

    //	delayFirst = false;
    //}

    //if (!funcResult)
    //{
    //	Message(infoPrintf);
    //}

    //return funcResult;
}
示例#27
0
std::shared_ptr<Notifications> ClientImpl::POST(in_addr_t ip, uint16_t port, std::string uri, std::string payload, Type type) {
  ILOG << "Sending " << ((type == Type::Confirmable) ? "confirmable " : "") << "POST request with URI=" << uri << '\n';
  return sendRequest(ip, port, Message(type, messageId_++, CoAP::Code::POST, newToken(), uri, payload));
}
//执行动作
bool implementsetting::Excute(void)
{
    if (!bLoadMap)
    {
        Message("SWITCH::Excute failed::load map failed!");
        return false;
    }

    bool funcResult = true;
    unsigned char txBuf[12] = { 0 }, rxBuf[12] = {0};
    unsigned char checkValue = 0;
    unsigned short *gpioBak = NULL;
    string ip;
    int replyCnt = 0; //尝试次数
    map<string, bool>hostIPEnableList;
    vector<string> actionQueue;

    txBuf[0]='W';

    //读入主机使能队列
    /*		for (map<string, stHostControl>::iterator itr = __hostCtrl.begin();
    			itr != __hostCtrl.end();
    			itr++)
    		{
    			hostIPEnableList[itr->second.ip] = itr->second.enable;
    		}*/

    for (map<string, string>::iterator itr = __ipmap.begin();
            itr != __ipmap.end();
            itr++)
    {
        hostIPEnableList[itr->second] = true;
    }

    for (map<string, unsigned short*>::iterator actionIter = __actionList.begin();
            actionIter != __actionList.end();
            actionIter++)
    {
        if (!hostIPEnableList[actionIter->first])continue;
        actionQueue.push_back(actionIter->first);
    }

    replyCnt = 0;

    while (true)
    {
        //下发开关指令队列
        for (map<string, unsigned short*>::iterator actionIter = __actionList.begin();
                actionIter != __actionList.end();
                actionIter++)
        {
            ip = actionIter->first;
            gpioBak = actionIter->second;

            if (!hostIPEnableList[ip])continue;

            checkValue = 0;
            for (int i = 1, j = 0; i < 11; j++)
            {
                txBuf[i] = gpioBak[j] % 256;
                checkValue ^= txBuf[i];
                i++;
                txBuf[i] = gpioBak[j] / 256;
                checkValue ^= txBuf[i];
                i++;
            }

            txBuf[11] = checkValue;

#ifdef __DEBUG_PRINT
            cout<<"<"<<ip<<">";
            for(int i=0; i<12; i++)
            {
                cout<<uppercase<<hex<<static_cast<int>(txBuf[i])<<" ";
            }
            cout<<endl;
#endif

            bool wrResult = false;
            int len = 12;

            for (int i = 0; i < 1; i++)
            {
                funcResult = wrResult = IOWrite(ip, (char*)txBuf, sizeof(txBuf));

                if (wrResult == false)continue;

                funcResult = wrResult = IORead(ip, (char*)rxBuf, &len);

                if (wrResult == false)continue;

                for (int j = 0; j < sizeof(txBuf); j++)
                {
                    if (rxBuf[j] != txBuf[j])
                    {
                        wrResult = false;
                        break;
                    }
                }

                funcResult = wrResult;
                if (wrResult == true)break;
            }

            if (!funcResult)break;
        }

        //break;
        if (replyCnt > 1 || funcResult)break;

        replyCnt++;

        //断开连接
        for (vector<string>::iterator itr = actionQueue.begin();
                itr != actionQueue.end();
                itr++)
        {
            IODisConnect(*itr);
        }

        //复位
        funcResult = IOResetWithList(actionQueue);

        //重连
        for (vector<string>::iterator itr = actionQueue.begin();
                itr != actionQueue.end();
                itr++)
        {
            IOConnectBegin(*itr);
        }

        bool wait = true;
        funcResult = true;
        vector<string> errHost;

        for (vector<string>::iterator itr = actionQueue.begin();
                itr != actionQueue.end();
                itr++)
        {
            if (!IOConnectEnd(*itr, wait ? 1000 : 100))
            {
                errHost.push_back(*itr);
                funcResult = false;
                break;
            }
            wait = false;
            //if (!funcResult)break;
            //LoadModuleState(*itr);
        }

        if (!funcResult)
        {
            string info("<MatrixSwitch>:[");

            for (vector<string>::iterator itr = errHost.begin();
                    itr != errHost.end();
                    itr++)
            {
                for (map<string,string>::iterator mtr = __ipmap.begin();
                        mtr != __ipmap.end();
                        mtr++)
                {
                    if (mtr->second == *itr)info.append(mtr->first + '@');
                }

                info.append(*itr+'/');
            }

            info.append("]:<Failed>");

            Message(info);

            break;
        }

        Delay(500);
    }

    return funcResult;
}
示例#29
0
std::shared_ptr<Notifications> ClientImpl::OBSERVE(in_addr_t ip, uint16_t port, std::string uri, Type type) {
  ILOG << "Sending " << ((type == Type::Confirmable) ? "confirmable " : "") << "OBSERVATION request with URI=" << uri << '\n';
  return sendObservation(ip, port, Message(type, messageId_++, CoAP::Code::GET, newToken(), uri));
}
示例#30
0
void Server::ReceiveThread(LPVOID lparam)
{
	//应当能接受一段字节流,然后交给下层的Message处理。得到一个处理结果存到全局变量MyJson中。
	//参数lparam是接受用的ReceiveSocket。
	//还需要调用本地的Client去建立一个反向的TCP链接
	//需要有能力调用对应的Client去反向回复
	SOCKET *ReceiveSocket=(SOCKET*)lparam;//得到建立连接的那个socket
	Client *respond_client=NULL;//本机上的客户机,指向全局的一个Client,或者在此线程中创建一个全局的Client,并用这个指针操作。需要在线程结束时释放。
	SOCKADDR_IN dest_add;//和本机建立通信的Client的地址
	string rcv;//接收到的字节流。
	int x=-1;
	int nAddrLen = sizeof(dest_add);
	//通过RCVSocket获得对方的地址
	if(::getpeername(*ReceiveSocket, (SOCKADDR*)&dest_add, &nAddrLen) != 0)
	{
		mtx->lock();
		std::cout<<"Get IP address by socket failed!"<<endl;
		this->exitSocket(*ReceiveSocket);//在server中删除这个socket
		mtx->unlock();
		return;
	}

	mtx->lock();
	cout<<"IP: "<<::inet_ntoa(dest_add.sin_addr)<<"  PORT: "<<ntohs(dest_add.sin_port)<<"开始向您通话!"<<endl;
	mtx->unlock();

	mtx->lock();
	respond_client=checkClientList(dest_add);//调用回调函数,checkClientList,并完成恢复Client的赋值
	mtx->unlock();
	//主循环

	while(1)
	{
		Message mess=Message();
		MyJson infomation=MyJson();
		try
		{
			rcv=this->receiveData(*ReceiveSocket);//接收信息,在这里线程会等待到接收到为止
		}
		catch(exception e)//TODO:应当处理此类异常!
		{
			cout<<"when Receive:"<<e.what();
			system("pause");
			//mtx->lock();
			//this->exitSocket(*ReceiveSocket);
			//deleteClient(respond_client);
			//mtx->unlock();
			//respond_client=NULL;
			return;
		}
		infomation=mess.getContent(rcv);//这里完成了从字节层到信息层的解包
		if(infomation.type_s=="exit")
		{	
			mtx->lock();
			//注销这个客户端,应当由回调函数完成
			this->exitSocket(*ReceiveSocket);//在acceptsocket中删除这个socket
			deleteClient(respond_client);
			mtx->unlock();
			cout<<inet_ntoa(dest_add.sin_addr)<<"下线了!"<<endl;
			respond_client=NULL;//它只是一个无辜的指针,告诉你内容在哪里,但请不要再本函数内操作它的内容。
			return ;
		}
		else
		{
			if(infomation.type_s=="text")
			{
				mtx->lock();
				respendClient(respond_client);
				infomation.showJson_in_console();
				cout<<endl;
				mtx->unlock();
			}
			else
			{
				//TODO:对其他的包类型进行处理,如果需要操作Client,依旧请使用回调函数。
				elsefunction(respond_client);
			}
		}
	}
	mtx->lock();
	this->exitSocket(*ReceiveSocket);
	mtx->unlock();
	delete respond_client;
	respond_client=NULL;
	return ;
}