MBChar * String::FromDoubleMB( MBChar * outStr, Double fValue, UInt iMinDigits, UInt iMaxDigits ) const
{
    // Clamp digits range
    DebugAssert( iMinDigits < iMaxDigits );
    if ( iMinDigits < 1 )  iMinDigits = 1;
	if ( iMaxDigits > 16 ) iMaxDigits = 16;
	UInt iRemaining = ( iMaxDigits - iMinDigits );

    // Zero case
    if ( fValue == 0.0 || fValue == -0.0 ) {
        *outStr++ = MBTEXT('0');
        *outStr++ = MBTEXT('.');
        *outStr++ = MBTEXT('0');
        while( iMinDigits > 2 ) {
            *outStr++ = MBTEXT('0');
            --iMinDigits;
        }
        *outStr = MBNULLBYTE;
        return outStr;
    }

    // Print sign
    if ( fValue < 0.0 ) {
        fValue = -fValue;
        *outStr++ = MBTEXT('-');
    }

    // Extract exponent
    Int iExponent = 0;
    while( fValue >= 1.0 ) {
        fValue *= 0.1;
        ++iExponent;
    }
    while( fValue < 0.1 ) {
        fValue *= 10.0;
        --iExponent;
    }
    while( iMinDigits > 0 ) {
        fValue *= 10.0;
        --iExponent;
        --iMinDigits;
    }

    // Print integer part
    Int64 iIntPart = (Int64)fValue;
    outStr = FromIntMB( outStr, iIntPart );

    // Print dot
    *outStr++ = MBTEXT('.');

    // Print fraction part
    Double fFractPart = ( fValue - (Double)iIntPart );
    while( iRemaining > 0 ) {
        fFractPart *= 10.0;
        --iRemaining;
    }
    outStr = FromIntMB( outStr, (Int64)fFractPart );

    // Remove trailing 0s
    --outStr;
    while( *outStr == MBTEXT('0') )
        --outStr;
    if ( *outStr == MBTEXT('.') ) {
        ++outStr;
        *outStr++ = MBTEXT('0');
    } else
        ++outStr;

    // Print exponent
    if ( iExponent != 0 ) {
        *outStr++ = MBTEXT('e');
        outStr = FromIntMB( outStr, iExponent );
    }

    *outStr = MBNULLBYTE;
    return outStr;
}
Example #2
0
//---------------------------------------------------------------------------
void __fastcall TKeyGenerator::StartGenerationThread()
{
  DebugAssert(FState == kgInitialized);
  FState = kgGenerating;
  new TKeyGenerationThread(this);
}
//---------------------------------------------------------------------------
void __fastcall TCustomWinConfiguration::SaveData(
  THierarchicalStorage * Storage, bool All)
{
  TGUIConfiguration::SaveData(Storage, All);

  // duplicated from core\configuration.cpp
  #define KEY(TYPE, VAR) Storage->Write ## TYPE(LASTELEM(UnicodeString(TEXT(#VAR))), VAR)
  REGCONFIG(true);
  #undef KEY

  if (FHistory->Count > 0)
  {
    if (Storage->OpenSubKey(L"History", true))
    {
      try
      {
        THistoryStrings * HistoryStrings;
        for (int Index = 0; Index < FHistory->Count; Index++)
        {
          HistoryStrings = dynamic_cast<THistoryStrings *>(FHistory->Objects[Index]);
          DebugAssert(HistoryStrings != NULL);
          if (All || HistoryStrings->Modified)
          {
            if (Storage->OpenSubKey(FHistory->Strings[Index], true))
            {
              try
              {
                Storage->WriteValues(HistoryStrings);
              }
              __finally
              {
                Storage->CloseSubKey();
              }
            }
          }
        }
      }
      __finally
      {
        Storage->CloseSubKey();
      }
    }

    if (Storage->OpenSubKey(L"HistoryParams", true))
    {
      try
      {
        THistoryStrings * HistoryStrings;
        for (int Index = 0; Index < FHistory->Count; Index++)
        {
          HistoryStrings = dynamic_cast<THistoryStrings *>(FHistory->Objects[Index]);
          DebugAssert(HistoryStrings != NULL);
          if (All || HistoryStrings->Modified)
          {
            bool HasData = false;
            for (int VIndex = 0; !HasData && (VIndex < HistoryStrings->Count); VIndex++)
            {
              HasData = (HistoryStrings->Objects[VIndex] != NULL);
            }

            if (!HasData)
            {
              Storage->RecursiveDeleteSubKey(FHistory->Strings[Index]);
            }
            else if (Storage->OpenSubKey(FHistory->Strings[Index], true))
            {
              try
              {
                Storage->ClearValues();
                for (int VIndex = 0; VIndex < HistoryStrings->Count; VIndex++)
                {
                  void * Data = HistoryStrings->Objects[VIndex];
                  Storage->WriteBinaryData(IntToStr(VIndex), &Data, sizeof(Data));
                }
              }
              __finally
              {
                Storage->CloseSubKey();
              }
            }
          }
        }
      }
      __finally
      {
        Storage->CloseSubKey();
      }
    }
  }
Example #4
0
int WINAPI ConfigureW(int item)
{
  DebugAssert(FarPlugin);
  TFarPluginGuard Guard;
  return static_cast<int>(FarPlugin->Configure(static_cast<intptr_t>(item)));
}
Example #5
0
//---------------------------------------------------------------------------
void KeyGenerationProgressUpdate(void * Thread,
  int Action, int Phase, int IProgress)
{
  DebugAssert(Thread);
  ((TKeyGenerationThread*)Thread)->ProgressUpdate(Action, Phase, IProgress);
}
Example #6
0
int WINAPI GetMinFarVersionW()
{
  DebugAssert(FarPlugin);
  TFarPluginGuard Guard;
  return static_cast<int>(FarPlugin->GetMinFarVersion());
}
Example #7
0
void WINAPI ExitFARW()
{
  DebugAssert(FarPlugin);
  TFarPluginGuard Guard;
  FarPlugin->ExitFAR();
}
Example #8
0
HTTPConnection::~HTTPConnection()
{
	DebugAssert(mReqs.empty());
	delete mSocket;
}
Example #9
0
WED_PackageMgr::~WED_PackageMgr()
{
	DebugAssert(gPackageMgr==this);
	gPackageMgr=NULL;
}
Example #10
0
int	pick_major_axis(
				vector<pair<Pmwx::Halfedge_handle, Pmwx::Halfedge_handle> >&	sides,				// Per side: inclusive range of half-edges "consolidated" into the sides.
				Polygon2&														bounds,			// Inset boundary in metric, first side matched to the list.
				Vector2&														v_x,
				Vector2&														v_y)
{
	// special case: if we find a block with exactly ONE right angle, the longer of the two
	// sides going into the right angle is hte major axis, full stop, we're done.
	int right_angle = -1;
	for(int i = 0; i < sides.size(); ++i)
	{
		int j = (i + 1) % sides.size();
		int k = (i + 2) % sides.size();
		Vector2	vx(Vector2(bounds[i],bounds[j]));
		Vector2	vy(Vector2(bounds[j],bounds[k]));
		vx.normalize();
		vy.normalize();
		double dot = fabs(vx.dot(vy));
		if(dot < 0.087155742747658)
		{
			if(right_angle == -1)
				right_angle = j;
			else
				right_angle = -2;		// "more than one right angle" flag - causes us to NOT try this algo.
		}
	}
	if(right_angle >= 0)
	{
		int prev = (right_angle + sides.size() - 1) % sides.size();
		int next = (right_angle +				 1) % sides.size();
		Vector2	vp(Vector2(bounds[prev],bounds[right_angle]));
		Vector2	vn(Vector2(bounds[right_angle],bounds[next]));
		double pl = vp.normalize();
		double nl = vn.normalize();
		if(pl > nl)
			v_x = vp;	
		else
			v_x = vn;
		v_y = v_x.perpendicular_ccw();
		
		return right_angle;
	}

	// THIS is the algo we shipped with - it tries to minimize the short side axis of the block.  This works
	// okay but tends to make the diagonal of diagonal cuts (like Broadway) the main axis since (by the pythag
	// theorem) that slightly reduces the block depth.

#if 0
	int shortest = -1;
	double	thinnest_so_far = 0.0;
	for(int i = 0; i < sides.size(); ++i)
	{
		Vector2 vx = Vector2(bounds.side(i).p1,bounds.side(i).p2);
		vx.normalize();
		Vector2 vy = vx.perpendicular_ccw();
		double bbox[4];
		bbox[0] = bbox[2] = vx.dot(Vector2(bounds[0]));
		bbox[1] = bbox[3] = vy.dot(Vector2(bounds[0]));
		for(int j = 0; j < sides.size(); ++j)
		{
			double x = vx.dot(Vector2(bounds[j]));
			double y = vy.dot(Vector2(bounds[j]));
			bbox[0] = dobmin2(bbox[0], x);
			bbox[1] = dobmin2(bbox[1], y);
			bbox[2] = dobmax2(bbox[2], x);
			bbox[3] = dobmax2(bbox[3], y);
		}
		double xdist = fabs(bbox[2]-bbox[0]);
		double ydist = fabs(bbox[3]-bbox[1]);
		double my_dist = dobmin2(xdist,ydist);
		if(shortest == -1 || my_dist < thinnest_so_far)
		{
			shortest = i;
			thinnest_so_far = my_dist;
			if(xdist < ydist)
			{
				v_x = vx.perpendicular_ccw();
				v_y = vy.perpendicular_ccw();
			}
			else
			{
				v_x = vx;
				v_y = vy;
			}
		}
	}
	
	DebugAssert(shortest >= 0);
	return shortest;
#endif

#if 1

//	#error This algo works 95% of the time, but 5% of the time it picks a slashed short end as the
//	#error long axis, which gives a long thin block a wrong axis alignment and a huge AABB.  Bad!


	// The basic idea: we want to pick the grid axis MOST aligned with the block such that
	// the major axis supports roads.  

	double best_corr = 0;
	double best = -1;
	Vector2	best_vec;

	bool elev_ok = false;

	int i, j, tries;
	for(tries = 0; tries < 2; ++tries)	
	{
		for(i = 0; i < sides.size(); ++i)
		if(elev_ok || ground_road_access_for_he(sides[i].first))	
		{
			double score = 0.0;
			Vector2 si = Vector2(bounds.side(i).p1,bounds.side(i).p2);
			si.normalize();
			Vector2 si_n = si.perpendicular_ccw();
			
			for(int j = 0; j < sides.size(); ++j)
			if(elev_ok || ground_road_access_for_he(sides[j].first))	
			{
				Vector2	sj(bounds.side(j).p1,bounds.side(j).p2);
				double my_corr = fltmax2(fabs(si.dot(sj)),fabs(si_n.dot(sj)));

				score += my_corr;
			}

			if(score > best_corr){
				best = i;
				best_corr = score;
				best_vec = si;
			}
		}
		
		if(best >= 0)
			break;
		elev_ok = true;
	}

	if(best >= 0)
	{
		Vector2	best_vec_n = best_vec.perpendicular_ccw();
		
		int longest = -1;
		double corr_len = -1;
		for(int i = 0; i < sides.size(); ++i)
		if(/*elev_ok ||*/ ground_road_access_for_he(sides[i].first))
		{
			Vector2 this_side(bounds.side(i).p1,bounds.side(i).p2);
			double len = this_side.normalize();
			double my_corr = fltmax2(fabs(best_vec.dot(this_side)), fabs(best_vec_n.dot(this_side)));
			if(my_corr > 0.996194698091746)
			{
				my_corr *= len;
				if(my_corr > corr_len)
				{
					longest = i;
					corr_len = my_corr;
				}			
			}
		}
		if(longest >= 0)
			best = longest;
	}
		
	v_x = Vector2(bounds.side(best).p1,bounds.side(best).p2);
	v_x.normalize();
	v_y = v_x.perpendicular_ccw();

	//printf("So far our best is %d, with axes %lf, %lf to %lf, %lf\n", best, v_x.dx,v_x.dy,v_y.dx,v_y.dy);
					

	double bbox[4];
	bbox[0] = bbox[2] = v_x.dot(Vector2(bounds[0]));
	bbox[1] = bbox[3] = v_y.dot(Vector2(bounds[0]));
	for(i = 1; i < sides.size(); ++i)
	{
		double va = v_x.dot(Vector2(bounds[i]));
		double vb = v_y.dot(Vector2(bounds[i]));
		bbox[0]=dobmin2(bbox[0], va);
		bbox[1]=dobmin2(bbox[1], vb);
		bbox[2]=dobmax2(bbox[2], va);
		bbox[3]=dobmax2(bbox[3], vb);
	}
	
	//printf("Our bbox is %lf,%lf to %lf,%lf\n", bbox[0],bbox[1],bbox[2],bbox[3]);

	if(0)
	if((bbox[2] - bbox[0]) < (bbox[3] - bbox[1]))
	{
		v_x = v_x.perpendicular_ccw();
		v_y = v_y.perpendicular_ccw();
		//printf("Must rotate, the winner was a SHORT side.\n");
	}

//	best = 0;
//	double best_dot = 0;
//	for(i = 0; i < sides.size(); ++i)
//	if(ground_road_access_for_he(sides[i].first))
//	{
//		Vector2	side_vec(bounds.side(i).p1,bounds.side(i).p2);
//		double slen = side_vec.normalize();
//		double corr = fabs(v_x.dot(side_vec));
//		if(corr > best_dot)
//		{
//			best = i;
//			corr = best_dot;
//		}
//	}
//	DebugAssert(best >= 0.0);
//	v_x = Vector2(bounds.side(best).p1,bounds.side(best).p2);
//	v_x.normalize();
//	v_y = v_x.perpendicular_ccw();
	return best;
#endif	
}
Example #11
0
HTTPRequest::~HTTPRequest()
{
	DebugAssert(mConnection == NULL);
	if (mDestFile)	fclose(mDestFile);
}
Example #12
0
bool	build_convex_polygon(
				Pmwx::Ccb_halfedge_circulator									ccb,
				vector<pair<Pmwx::Halfedge_handle, Pmwx::Halfedge_handle> >&	sides,
				const CoordTranslator2&											trans,
				Polygon2&														metric_bounds,
				double															max_err_mtrs,
				double															min_side_len)
{
	double	e_sq = max_err_mtrs*max_err_mtrs;
	sides.clear();
	metric_bounds.clear();
	
	Pmwx::Ccb_halfedge_circulator circ(ccb);
//	Bbox2				bounds;
//	
//	do {
//		bounds += cgal2ben(circ->source()->point());
//	} while (++circ != ccb);

	Pmwx::Ccb_halfedge_circulator start,next;
	start = ccb;
	do {
		--start;
		if(!sides_can_merge(start,ccb))
			break;
		if(!within_err_metric(start,ccb,trans,e_sq))
			break;		
	} while(start != ccb);
	++start;
	
	// now we can go around.

	circ = start;
	//int ne = count_circulator(start);
	//printf("Poly has %d sides.\n", ne);
	do {
	 
		Pmwx::Ccb_halfedge_circulator stop(circ);
		do {
			++stop;
		} while(sides_can_merge(circ,stop) && within_err_metric(circ,stop,trans,e_sq) && stop != start);
	
		--stop;
		//printf("Pushing side of %d, %d\n", circulator_distance_to(start, circ),circulator_distance_to(start,stop));
		sides.push_back(pair<Pmwx::Halfedge_handle,Pmwx::Halfedge_handle>(circ, stop));
		++stop;
		circ = stop;
	
	} while(circ != start);
	
	if(sides.size() < 3)	
	{
		//debug_mesh_point(bounds.centroid(),1,1,1);
		return false;
	}
	
	int i, j, k;
	
	vector<Segment2>	msides;
	for(i = 0; i < sides.size(); ++i)
	{
		j = (i + 1) % sides.size();		
		DebugAssert(sides[i].second->target() == sides[j].first->source());
		msides.push_back(Segment2(
						trans.Forward(cgal2ben(sides[i].first->source()->point())),
						trans.Forward(cgal2ben(sides[i].second->target()->point()))));						
	}	
	vector<Segment2>	debug(msides);
	for(i = 0; i < sides.size(); ++i)
	{
		j = (i + 1) % sides.size();		
		Vector2	v1(msides[i].p1,msides[i].p2);
		Vector2	v2(msides[j].p1,msides[j].p2);
		v1.normalize();
		v2.normalize();
		if(v1.dot(v2) > 0.9998 ||
			!v1.left_turn(v2))
		{
			//debug_mesh_point(trans.Reverse(msides[i].p2),1,0,0);
			return false;
		}
		double w = width_for_he(sides[i].first);
		if(w)
		{
			v1 = v1.perpendicular_ccw();
			v1 *= w;
			msides[i].p1 += v1;
			msides[i].p2 += v1;
		}
	}
	for(j = 0; j < sides.size(); ++j)
	{
		i = (j + sides.size() - 1) % sides.size();
		Line2 li(msides[i]), lj(msides[j]);
		Point2	p;
		if(!li.intersect(lj,p))
		{
			Assert(!"Failure to intersect.\n");
			return false;
		}
		metric_bounds.push_back(p);
	}
	
	for(i = 0; i < metric_bounds.size(); ++i)
	{
		j = (i + 1) % metric_bounds.size();
		k = (i + 2) % metric_bounds.size();
		if(metric_bounds.side(i).squared_length() < (min_side_len*min_side_len))
		{
			//debug_mesh_line(trans.Reverse(metric_bounds.side(i).p1),trans.Reverse(metric_bounds.side(i).p2),1,1,0,1,1,0);
			return false;
		}
		if(!left_turn(metric_bounds[i],metric_bounds[j],metric_bounds[k]))
		{
			//debug_mesh_point(trans.Reverse(metric_bounds[j]),1,1,0);
			return false;
		}
		if(Vector2(msides[i].p1,msides[i].p2).dot(Vector2(metric_bounds[i],metric_bounds[j])) < 0.0)
		{
			//debug_mesh_line(trans.Reverse(msides[i].p1),trans.Reverse(msides[i].p2),1,0,0,1,0,0);
			return false;
		}
	}
	DebugAssert(metric_bounds.size() == msides.size());
	DebugAssert(msides.size() == sides.size());
		
	return true;
}
Example #13
0
	bool is_locked(Block_2::Vertex_handle v) const
	{
		DebugAssert(v->degree() == 2);
		Block_2::Halfedge_handle he = v->incident_halfedges();
		return he->face()->is_unbounded() || he->twin()->face()->is_unbounded();
	}
Example #14
0
// We build a block from scratch with a bunch of polygons.  Note that where polygons overlap, the earliest one in the block will "win" - that is, unneeded halfedges
// WILL exist, but the "tags" will match the lower prio blokc data.
void	create_block(
					Block_2&									block,
					const vector<BLOCK_face_data>&				in_data,
					const vector<Block_2::X_monotone_curve_2>&	in_bounds,
					int											unbounded_idx)
{
	block.clear();
	
	#if DEV
		for(int n = 0; n < in_data.size(); ++n)
			if(in_data[n].usage == usage_Polygonal_Feature)
				DebugAssert(in_data[n].feature != 0);
	#endif
	
	// First we are going to build up a curve list and bulk insert them all.  Each curve has the polygon number as its data.
	// This should be faster than doing a series of piece-wise inserts.

#if 0
	vector<Block_2::X_monotone_curve_2>	keep;
	set<pair<Point_2,Point_2> >	we_have;
	for(int n = 0; n < in_bounds.size(); ++n)
	{
		pair<Point_2,Point_2>	s(in_bounds[n].source(),in_bounds[n].target());
		if(s.first < s.second) swap(s.first,s.second);
		if(we_have.count(s) == 0)
		{
			keep.push_back(in_bounds[n]);
			we_have.insert(s);
		}
	}

	CGAL::insert(block, keep.begin(), keep.end());
#endif	

	CGAL::insert(block, in_bounds.begin(), in_bounds.end());

#if 0
	FastCDT	cdt;
	FastCDT::Face_handle hint;
	vector<pair<FastCDT::Vertex_handle, FastCDT::Vertex_handle> >	vv;
	
	set<pair<FastCDT::Vertex_handle, FastCDT::Vertex_handle> > we_have;
	
	for(int n = 0; n < in_bounds.size(); ++n)
	{
		pair<FastCDT::Vertex_handle,FastCDT::Vertex_handle>	r;
		r.first = cdt.insert(C(in_bounds[n].source()),hint);
		hint = r.first->face();
		r.second = cdt.insert(C(in_bounds[n].target()),hint);
		hint = r.second->face();
		if(r.first < r.second)	swap(r.first,r.second);
		if(we_have.count(r) == 0)
		{
			we_have.insert(r);
			vv.push_back(r);
		}	
	}
	for(int n = 0; n < vv.size(); ++n)
	{
		DebugAssert(vv[n].first != vv[n].second);
		cdt.insert_constraint(vv[n].first,vv[n].second);
	}
#endif	

	// Now we go back and do a search from the outside in, toggling our "membership" each time we cross a bounding edge, to keep track of
	// which face we are in.

	for(Block_2::Face_iterator f = block.faces_begin(); f != block.faces_end(); ++f)
			f->set_visited(false);

	apply_properties_visitor	visitor;
	visitor.feature_map = &in_data;
	// What is this?  The FIRST contour is considered the contour that tags the unbounded polygon.  So we "start" with this polygon in effect.
	if(unbounded_idx != -1)
		visitor.initial.insert(unbounded_idx);
	
	visitor.Visit(&block);

	#if DEV
	for (Block_2::Face_iterator f = block.faces_begin(); f != block.faces_end(); ++f)
	if(f->data().usage == usage_Polygonal_Feature)
				DebugAssert(f->data().feature != 0);
	#endif

}
void	WED_DoSplit(IResolver * resolver)
{
	ISelection * sel = WED_GetSelect(resolver);
	IOperation * op = dynamic_cast<IOperation *>(sel);

	vector<WED_Thing *> who;
	hack_t	info;
	info.first = sel;
	info.second = &who;

	sel->IterateSelectionOr(collect_splits, &info);
	if (who.empty()) return;

	op->StartOperation("Split Segments.");

	for (vector<WED_Thing *>::iterator w = who.begin(); w != who.end(); ++w)
	{
		WED_Thing * parent = (*w)->GetParent();
		IGISPointSequence * seq = dynamic_cast<IGISPointSequence *>(parent);
		WED_Thing * new_w = (WED_Thing *) (*w)->Clone();

		IGISPoint * as_p = dynamic_cast<IGISPoint *>(new_w);
		IGISPoint_Bezier * as_bp = dynamic_cast<IGISPoint_Bezier *>(new_w);

		Segment2	seg;
		Bezier2		bez;

//		set<int> attrs;
//		node->GetAttributes(attrs);
///		new_node->SetAttributes(attrs);

		if (seq->GetSide(gis_Geo,(*w)->GetMyPosition(),seg,bez))
		{
			IGISPoint_Bezier * pre = dynamic_cast<IGISPoint_Bezier *>(*w);
			IGISPoint_Bezier * follow = dynamic_cast<IGISPoint_Bezier *>(parent->GetNthChild(((*w)->GetMyPosition()+1) % parent->CountChildren()));
			DebugAssert(as_bp);
			DebugAssert(pre);
			DebugAssert(follow);
			Bezier2	b1, b2;
			bez.partition(b1,b2);
			as_bp->SetLocation(gis_Geo,b2.p1);
			as_bp->SetSplit(false);
			as_bp->SetControlHandleHi(gis_Geo,b2.c1);
			pre->SetSplit(true);
			pre->SetControlHandleHi(gis_Geo,b1.c1);
			follow->SetSplit(true);
			follow->SetControlHandleLo(gis_Geo,b2.c2);
			if(as_bp->HasLayer(gis_UV))
			{
				seq->GetSide(gis_UV,(*w)->GetMyPosition(),seg,bez);
				bez.partition(b1,b2);
				as_bp->SetLocation(gis_UV,b2.p1);
				as_bp->SetControlHandleHi(gis_UV,b2.c1);
				as_bp->SetControlHandleLo(gis_UV,b1.c2);
				pre->SetControlHandleHi(gis_UV,b1.c1);
				follow->SetControlHandleLo(gis_UV,b2.c2);			
			}
		}
		else
		{
			DebugAssert(as_p);
			as_p->SetLocation(gis_Geo,seg.midpoint());
			if(as_p->HasLayer(gis_UV))
			{
				seq->GetSide(gis_UV,(*w)->GetMyPosition(),seg,bez);			
				as_p->SetLocation(gis_UV,seg.midpoint());
			}
		}
		new_w->SetParent(parent, (*w)->GetMyPosition() + 1);
		string name;
		new_w->GetName(name);
		name += ".1";
		new_w->SetName(name);

		sel->Insert(new_w);
	}

	op->CommitOperation();
}
void CopyToClipboard(UnicodeString AText)
{
  DebugAssert(FarPlugin != nullptr);
  FarPlugin->FarCopyToClipboard(AText);
}
Example #17
0
void TCopyParamType::DoGetInfoStr(
  const UnicodeString & Separator, intptr_t Options,
  UnicodeString & Result, bool & SomeAttrIncluded,
  const UnicodeString & Link, UnicodeString & ScriptArgs, bool & NoScriptArgs, /*TAssemblyLanguage Language, UnicodeString & AssemblyCode,*/
  bool & NoCodeProperties) const
{
  TCopyParamType Defaults;

  bool SomeAttrExcluded = false;
  NoScriptArgs = false;
  NoCodeProperties = false;
  SomeAttrIncluded = false;
  #define ADD(STR, EXCEPT) \
    if (FLAGCLEAR(Options, EXCEPT)) \
    { \
      AddToList(Result, (STR), Separator); \
      SomeAttrIncluded = true; \
    } \
    else \
    { \
      SomeAttrExcluded = true; \
    }

  bool AsciiFileMaskDiffers = (GetTransferMode() == tmAutomatic) && !(GetAsciiFileMask() == Defaults.GetAsciiFileMask());
  bool TransferModeDiffers = ((GetTransferMode() != Defaults.GetTransferMode()) || AsciiFileMaskDiffers);

  if (FLAGCLEAR(Options, cpaIncludeMaskOnly | cpaNoTransferMode))
  {
    // Adding Transfer type unconditionally
    bool FormatMask;
    int Ident;
    switch (GetTransferMode())
    {
      case tmBinary:
        FormatMask = false;
        Ident = 2;
        break;
      case tmAscii:
        FormatMask = false;
        Ident = 3;
        break;
      case tmAutomatic:
      default:
        FormatMask = !(GetAsciiFileMask() == Defaults.GetAsciiFileMask());
        Ident = FormatMask ? 4 : 5;
        break;
    }
    UnicodeString S = FORMAT(LoadStrPart(COPY_INFO_TRANSFER_TYPE2, 1).c_str(),
      LoadStrPart(COPY_INFO_TRANSFER_TYPE2, Ident).c_str());
    if (FormatMask)
    {
      S = FORMAT(S.c_str(), GetAsciiFileMask().GetMasks().c_str());
    }
    AddToList(Result, S, Separator);

    if (TransferModeDiffers)
    {
      ADD("", cpaIncludeMaskOnly | cpaNoTransferMode);

      /*ScriptArgs += RtfSwitchValue(TRANSFER_SWITCH, Link, TransferModeNames[TransferMode]);
      const wchar_t * TransferModeMembers[] = { L"Binary", L"Ascii", L"Automatic" };
      AssemblyCode += AssemblyProperty(
        Language, TransferOptionsClassName, L"TransferMode", L"TransferMode", TransferModeMembers[TransferMode], false);
      if (AsciiFileMaskDiffers)
      {
        NoScriptArgs = true;
        NoCodeProperties = true;
      }*/
    }
  }
  else
  {
    if (TransferModeDiffers)
    {
      SomeAttrExcluded = true;
      NoScriptArgs = true;
      NoCodeProperties = true;
    }
  }

  if (GetFileNameCase() != Defaults.GetFileNameCase())
  {
    ADD(FORMAT(LoadStrPart(COPY_INFO_FILENAME, 1).c_str(),
      LoadStrPart(COPY_INFO_FILENAME, GetFileNameCase() + 2).c_str()),
      cpaIncludeMaskOnly);

    NoScriptArgs = true;
    NoCodeProperties = true;
  }

  if ((GetInvalidCharsReplacement() == NoReplacement) !=
        (Defaults.GetInvalidCharsReplacement() == NoReplacement))
  {
    DebugAssert(GetInvalidCharsReplacement() == NoReplacement);
    if (GetInvalidCharsReplacement() == NoReplacement)
    {
      ADD(LoadStr(COPY_INFO_DONT_REPLACE_INV_CHARS).c_str(), cpaIncludeMaskOnly);
    }

    NoScriptArgs = true;
    NoCodeProperties = true;
  }

  if ((GetPreserveRights() != Defaults.GetPreserveRights()) ||
      (GetPreserveRights() &&
       ((GetRights() != Defaults.GetRights()) || (GetAddXToDirectories() != Defaults.GetAddXToDirectories()))))
  {
    const int Except = cpaIncludeMaskOnly | cpaNoRights;
    if (DebugAlwaysTrue(GetPreserveRights()))
    {
      UnicodeString RightsStr = GetRights().GetText();
      if (GetAddXToDirectories())
      {
        RightsStr += L", " + LoadStr(COPY_INFO_ADD_X_TO_DIRS);
      }
      ADD(FORMAT(LoadStr(COPY_INFO_PERMISSIONS).c_str(), RightsStr.c_str()),
        Except);
      if (FLAGCLEAR(Options, Except))
      {
//        ScriptArgs += RtfSwitchValue(PERMISSIONS_SWITCH, Link, Rights.Octal);

//        const UnicodeString FilePermissionsClassName = L"FilePermissions";
//        const bool Inline = true;
//        UnicodeString FilePermissions =
//          AssemblyNewClassInstanceStart(Language, FilePermissionsClassName, Inline) +
//          AssemblyProperty(Language, FilePermissionsClassName, L"Octal", Rights.Octal, Inline) +
//          AssemblyNewClassInstanceEnd(Language, Inline);

//        AssemblyCode += AssemblyPropertyRaw(Language, TransferOptionsClassName, L"FilePermissions", FilePermissions, false);
      }
    }

    if ((GetAddXToDirectories() != Defaults.GetAddXToDirectories()) && FLAGCLEAR(Options, Except))
    {
      NoScriptArgs = true;
      NoCodeProperties = true;
    }
  }

  bool APreserveTimeDirs = GetPreserveTime() && GetPreserveTimeDirs();
  if ((GetPreserveTime() != Defaults.GetPreserveTime()) || (APreserveTimeDirs != Defaults.GetPreserveTimeDirs()))
  {
    bool AddPreserveTime = false;
    UnicodeString Str = LoadStr(GetPreserveTime() ? COPY_INFO_TIMESTAMP : COPY_INFO_DONT_PRESERVE_TIME);

    const int ExceptDirs = cpaNoPreserveTimeDirs;
    if (APreserveTimeDirs != Defaults.GetPreserveTimeDirs())
    {
      if (DebugAlwaysTrue(GetPreserveTimeDirs()))
      {
        if (FLAGCLEAR(Options, ExceptDirs))
        {
          Str = FMTLOAD(COPY_INFO_PRESERVE_TIME_DIRS, (Str));
          AddPreserveTime = true;
        }
      }
      ADD("", ExceptDirs);
    }

    const int Except = cpaIncludeMaskOnly | cpaNoPreserveTime;
    if (GetPreserveTime() != Defaults.GetPreserveTime())
    {
      if (FLAGCLEAR(Options, Except))
      {
        AddPreserveTime = true;
      }
      ADD(L"", Except);
    }

    if (AddPreserveTime)
    {
      AddToList(Result, Str, Separator);
    }

    if (FLAGCLEAR(Options, Except))
    {
      if (GetPreserveTime())
      {
        if (GetPreserveTimeDirs() && FLAGCLEAR(Options, ExceptDirs))
        {
          //ScriptArgs += RtfSwitchValue(PRESERVETIME_SWITCH, Link, PRESERVETIMEDIRS_SWITCH_VALUE);
          NoCodeProperties = true;
        }
        else
        {
          DebugFail(); // should never get here
          //ScriptArgs += RtfSwitch(PRESERVETIME_SWITCH, Link);
        }
      }
      else
      {
//        ScriptArgs += RtfSwitch(NOPRESERVETIME_SWITCH, Link);
//        AssemblyCode += AssemblyProperty(Language, TransferOptionsClassName, L"PreserveTimestamp", false, false);
      }
    }
  }

  if ((GetPreserveRights() || GetPreserveTime()) &&
      (GetIgnorePermErrors() != Defaults.GetIgnorePermErrors()))
  {
    if (DebugAlwaysTrue(GetIgnorePermErrors()))
    {
      const int Except = cpaIncludeMaskOnly | cpaNoIgnorePermErrors;
      ADD(LoadStr(COPY_INFO_IGNORE_PERM_ERRORS), Except);
      if (FLAGCLEAR(Options, Except))
      {
        NoScriptArgs = true;
        NoCodeProperties = true;
      }
    }
  }

  if (GetPreserveReadOnly() != Defaults.GetPreserveReadOnly())
  {
    if (DebugAlwaysTrue(GetPreserveReadOnly()))
    {
      const int Except = cpaIncludeMaskOnly | cpaNoPreserveReadOnly;
      ADD(LoadStr(COPY_INFO_PRESERVE_READONLY), Except);
      if (FLAGCLEAR(Options, Except))
      {
        NoScriptArgs = true;
        NoCodeProperties = true;
      }
    }
  }

  if (GetCalculateSize() != Defaults.GetCalculateSize())
  {
    if (DebugAlwaysTrue(!GetCalculateSize()))
    {
      ADD(LoadStr(COPY_INFO_DONT_CALCULATE_SIZE), cpaIncludeMaskOnly);
      // Always false in scripting, in assembly controlled by use of FileTransferProgress
    }
  }

  if (GetClearArchive() != Defaults.GetClearArchive())
  {
    if (DebugAlwaysTrue(GetClearArchive()))
    {
      const int Except = cpaIncludeMaskOnly | cpaNoClearArchive;
      ADD(LoadStr(COPY_INFO_CLEAR_ARCHIVE), Except);
      if (FLAGCLEAR(Options, Except))
      {
        NoScriptArgs = true;
        NoCodeProperties = true;
      }
    }
  }

  if ((GetTransferMode() == tmAscii) || (GetTransferMode() == tmAutomatic))
  {
    if (GetRemoveBOM() != Defaults.GetRemoveBOM())
    {
      if (DebugAlwaysTrue(GetRemoveBOM()))
      {
        const int Except = cpaIncludeMaskOnly | cpaNoRemoveBOM | cpaNoTransferMode;
        ADD(LoadStr(COPY_INFO_REMOVE_BOM), Except);
        if (FLAGCLEAR(Options, Except))
        {
          NoScriptArgs = true;
          NoCodeProperties = true;
        }
      }
    }

    if (GetRemoveCtrlZ() != Defaults.GetRemoveCtrlZ())
    {
      if (DebugAlwaysTrue(GetRemoveCtrlZ()))
      {
        const int Except = cpaIncludeMaskOnly | cpaNoRemoveCtrlZ | cpaNoTransferMode;
        ADD(LoadStr(COPY_INFO_REMOVE_CTRLZ),Except);
        if (FLAGCLEAR(Options, Except))
        {
          NoScriptArgs = true;
          NoCodeProperties = true;
        }
      }
    }
  }

  if (!(GetIncludeFileMask() == Defaults.GetIncludeFileMask()))
  {
    ADD(FORMAT(LoadStr(COPY_INFO_FILE_MASK).c_str(), GetIncludeFileMask().GetMasks().c_str()),
      cpaNoIncludeMask);

//    ScriptArgs += RtfSwitch(FILEMASK_SWITCH, Link, IncludeFileMask.Masks);
//    AssemblyCode += AssemblyProperty(Language, TransferOptionsClassName, L"FileMask", IncludeFileMask.Masks, false);
  }

  DebugAssert(FTransferSkipList.get() == nullptr);
  DebugAssert(FTransferResumeFile.IsEmpty());

  if (GetCPSLimit() > 0)
  {
    intptr_t LimitKB = intptr_t(GetCPSLimit() / 1024);
    ADD(FMTLOAD(COPY_INFO_CPS_LIMIT2, (LimitKB)), cpaIncludeMaskOnly);

//    ScriptArgs += RtfSwitch(SPEED_SWITCH, Link, LimitKB);
//    AssemblyCode += AssemblyProperty(Language, TransferOptionsClassName, L"Speed", LimitKB, false);
  }

  if (GetNewerOnly() != Defaults.GetNewerOnly())
  {
    if (DebugAlwaysTrue(GetNewerOnly()))
    {
      const int Except = cpaIncludeMaskOnly | cpaNoNewerOnly;
      ADD(StripHotkey(LoadStr(COPY_PARAM_NEWER_ONLY)), Except);
      if (FLAGCLEAR(Options, Except))
      {
//        ScriptArgs += RtfSwitch(NEWERONLY_SWICH, Link);
        NoCodeProperties = true;
      }
    }
  }

  bool ResumeThresholdDiffers = ((GetResumeSupport() == rsSmart) && (GetResumeThreshold() != Defaults.GetResumeThreshold()));
  if (((GetResumeSupport() != Defaults.GetResumeSupport()) || ResumeThresholdDiffers) &&
      (GetTransferMode() != tmAscii) && FLAGCLEAR(Options, cpaNoResumeSupport))
  {
    UnicodeString Value;
    UnicodeString CodeState;
    intptr_t ResumeThresholdKB = (GetResumeThreshold() / 1024);
    switch (GetResumeSupport())
    {
      case rsOff:
        Value = ToggleNames[ToggleOff];
        CodeState = L"Off";
        break;

      case rsOn:
        Value = ToggleNames[ToggleOn];
        CodeState = L"On";
        break;

      case rsSmart:
        Value = IntToStr(ResumeThresholdKB);
        break;
    }
//    ScriptArgs += RtfSwitchValue(RESUMESUPPORT_SWITCH, Link, Value);

    const UnicodeString ResumeSupportClassName = L"TransferResumeSupport";
//    const bool Inline = true;
//    UnicodeString ResumeSupportCode =
//      AssemblyNewClassInstanceStart(Language, ResumeSupportClassName, Inline);
    if (GetResumeSupport() == rsSmart)
    {
//      ResumeSupportCode += AssemblyProperty(Language, ResumeSupportClassName, L"Threshold", ResumeThresholdKB, Inline);
    }
    else
    {
//      ResumeSupportCode += AssemblyProperty(Language, ResumeSupportClassName, L"State", L"TransferResumeSupportState", CodeState, Inline);
    }
//    ResumeSupportCode += AssemblyNewClassInstanceEnd(Language, Inline);

//    AssemblyCode += AssemblyPropertyRaw(Language, TransferOptionsClassName, L"ResumeSupport", ResumeSupportCode, false);
  }

  if (SomeAttrExcluded)
  {
    Result += (Result.IsEmpty() ? UnicodeString() : Separator) +
      FORMAT(LoadStrPart(COPY_INFO_NOT_USABLE, 1).c_str(),
        LoadStrPart(COPY_INFO_NOT_USABLE, (SomeAttrIncluded ? 2 : 3)).c_str());
  }
  else if (Result.IsEmpty())
  {
    Result = LoadStr(COPY_INFO_DEFAULT);
  }
  #undef ADD
}
void TSessionLog::DoAddStartupInfo(TSessionData *Data)
{
  if (Data == nullptr)
  {
    AddSeparator();
    UnicodeString OS = WindowsVersionLong();
    AddToList(OS, WindowsProductName(), L" - ");
    ADF("NetBox %s (OS %s)", FConfiguration->GetProductVersionStr(), OS);
    {
      std::unique_ptr<THierarchicalStorage> Storage(FConfiguration->CreateConfigStorage());
      DebugAssert(Storage.get());
      ADF("Configuration: %s", Storage->GetSource());
    }

#if 0
    typedef BOOL (WINAPI * TGetUserNameEx)(EXTENDED_NAME_FORMAT NameFormat, LPWSTR lpNameBuffer, PULONG nSize);
    HINSTANCE Secur32 = LoadLibrary(L"secur32.dll");
    TGetUserNameEx GetUserNameEx =
      (Secur32 != nullptr) ? reinterpret_cast<TGetUserNameEx>(::GetProcAddress(Secur32, "GetUserNameExW")) : nullptr;
    wchar_t UserName[UNLEN + 1];
    ULONG UserNameSize = _countof(UserName);
    if ((GetUserNameEx == nullptr) || DebugAlwaysFalse(!GetUserNameEx(NameSamCompatible, (LPWSTR)UserName, &UserNameSize)))
    {
      wcscpy_s(UserName, UNLEN, L"<Failed to retrieve username>");
    }
#endif // #if 0
    UnicodeString LogStr;
    if (FConfiguration->GetLogProtocol() <= 0)
    {
      LogStr = L"Normal";
    }
    else if (FConfiguration->GetLogProtocol() == 1)
    {
      LogStr = L"Debug 1";
    }
    else if (FConfiguration->GetLogProtocol() >= 2)
    {
      LogStr = L"Debug 2";
    }
#if 0
    if (FConfiguration->GetLogSensitive())
    {
      LogStr += L", Logging passwords";
    }
#endif // #if 0
    if (FConfiguration->GetLogMaxSize() > 0)
    {
      LogStr += FORMAT(L", Rotating after: %s", SizeToStr(FConfiguration->GetLogMaxSize()));
      if (FConfiguration->GetLogMaxCount() > 0)
      {
        LogStr += FORMAT(L", Keeping at most %d logs", FConfiguration->GetLogMaxCount());
      }
    }
#if 0
    ADF("Log level: %s", LogStr);
    ADF("Local account: %s", UserName);
#endif // #if 0
    ADF("Working directory: %s", GetCurrentDir());
    ADF("Process ID: %d", intptr_t(GetCurrentProcessId()));
#if 0
    ADF("Command-line: %s", GetCmdLineLog());
    if (FConfiguration->GetLogProtocol() >= 1)
    {
      AddOptions(GetGlobalOptions());
    }
#endif // #if 0
    ADF("Time zone: %s", GetTimeZoneLogString());
    if (!AdjustClockForDSTEnabled())
    {
      ADF("Warning: System option \"Automatically adjust clock for Daylight Saving Time\" is disabled, timestamps will not be represented correctly");
    }
#if 0
    ADF("Login time: %s", dt);
#endif // #if 0
    AddSeparator();
  }
  else
  {
#if 0
    ADF("Session name: %s (%s)", Data->GetSessionName(), Data->GetSource());
    ADF("Host name: %s (Port: %d)", Data->GetHostNameExpanded(), Data->GetPortNumber());
    ADF("User name: %s (Password: %s, Key file: %s, Passphrase: %s)",
      Data->GetUserNameExpanded(), LogSensitive(Data->GetPassword()),
      LogSensitive(Data->GetPublicKeyFile()), LogSensitive(Data->GetPassphrase()))
#endif // #if 0
    if (Data->GetUsesSsh())
    {
      ADF("Tunnel: %s", BooleanToEngStr(Data->GetTunnel()));
      if (Data->GetTunnel())
      {
        ADF("Tunnel: Host name: %s (Port: %d)", Data->GetTunnelHostName(), Data->GetTunnelPortNumber());
#if 0
        ADF("Tunnel: User name: %s (Password: %s, Key file: %s)",
          Data->GetTunnelUserName(), BooleanToEngStr(!Data->GetTunnelPassword().IsEmpty()),
          BooleanToEngStr(!Data->GetTunnelPublicKeyFile().IsEmpty()));
        ADF("Tunnel: Local port number: %d", Data->GetTunnelLocalPortNumber());
#endif // #if 0
      }
    }
    ADF("Transfer Protocol: %s", Data->GetFSProtocolStr());
    ADF("Code Page: %d", Data->GetCodePageAsNumber());
    if (Data->GetUsesSsh() || (Data->GetFSProtocol() == fsFTP))
    {
      TPingType PingType;
      intptr_t PingInterval;
      if (Data->GetFSProtocol() == fsFTP)
      {
        PingType = Data->GetFtpPingType();
        PingInterval = Data->GetFtpPingInterval();
      }
      else
      {
        PingType = Data->GetPingType();
        PingInterval = Data->GetPingInterval();
      }
      ADF("Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
        EnumName(PingType, PingTypeNames), PingInterval, Data->GetTimeout());
      ADF("Disable Nagle: %s",
        BooleanToEngStr(Data->GetTcpNoDelay()));
    }
    TProxyMethod ProxyMethod = Data->GetActualProxyMethod();
    {
      UnicodeString fp = FORMAT(L"FTP proxy %d", Data->GetFtpProxyLogonType());
      ADF("Proxy: %s",
        (Data->GetFtpProxyLogonType() != 0) ? fp : EnumName(ProxyMethod, ProxyMethodNames));
    }
    if ((Data->GetFtpProxyLogonType() != 0) || (ProxyMethod != ::pmNone))
    {
      ADF("ProxyHostName: %s (Port: %d); ProxyUsername: %s; Passwd: %s",
        Data->GetProxyHost(), Data->GetProxyPort(),
        Data->GetProxyUsername(), BooleanToEngStr(!Data->GetProxyPassword().IsEmpty()));
      if (ProxyMethod == pmTelnet)
      {
        ADF("Telnet command: %s", Data->GetProxyTelnetCommand());
      }
      if (ProxyMethod == pmCmd)
      {
        ADF("Local command: %s", Data->GetProxyLocalCommand());
      }
    }
    if (Data->GetUsesSsh() || (Data->GetFSProtocol() == fsFTP))
    {
      ADF("Send buffer: %d", Data->GetSendBuf());
    }
    if (Data->GetUsesSsh())
    {
      ADF("SSH protocol version: %s; Compression: %s",
        Data->GetSshProtStr(), BooleanToEngStr(Data->GetCompression()));
      ADF("Bypass authentication: %s",
        BooleanToEngStr(Data->GetSshNoUserAuth()));
      ADF("Try agent: %s; Agent forwarding: %s; TIS/CryptoCard: %s; KI: %s; GSSAPI: %s",
        BooleanToEngStr(Data->GetTryAgent()), BooleanToEngStr(Data->GetAgentFwd()), BooleanToEngStr(Data->GetAuthTIS()),
        BooleanToEngStr(Data->GetAuthKI()), BooleanToEngStr(Data->GetAuthGSSAPI()));
      if (Data->GetAuthGSSAPI())
      {
        ADF("GSSAPI: Forwarding: %s",
          BooleanToEngStr(Data->GetGSSAPIFwdTGT()));
      }
      ADF("Ciphers: %s; Ssh2DES: %s",
        Data->GetCipherList(), BooleanToEngStr(Data->GetSsh2DES()));
      ADF("KEX: %s", Data->GetKexList());
      UnicodeString Bugs;
      for (intptr_t Index = 0; Index < BUG_COUNT; ++Index)
      {
        AddToList(Bugs, EnumName(Data->GetBug(static_cast<TSshBug>(Index)), AutoSwitchNames), L",");
      }
      ADF("SSH Bugs: %s", Bugs);
      ADF("Simple channel: %s", BooleanToEngStr(Data->GetSshSimple()));
      ADF("Return code variable: %s; Lookup user groups: %s",
        Data->GetDetectReturnVar() ? UnicodeString(L"Autodetect") : Data->GetReturnVar(),
        EnumName(Data->GetLookupUserGroups(), AutoSwitchNames));
      ADF("Shell: %s", Data->GetShell().IsEmpty() ? UnicodeString(L"default") : Data->GetShell());
      ADF("EOL: %s, UTF: %s", EnumName(Data->GetEOLType(), EOLTypeNames), EnumName(Data->GetNotUtf(), NotAutoSwitchNames)); // NotUtf duplicated in FTP branch
      ADF("Clear aliases: %s, Unset nat.vars: %s, Resolve symlinks: %s; Follow directory symlinks: %s",
        BooleanToEngStr(Data->GetClearAliases()), BooleanToEngStr(Data->GetUnsetNationalVars()),
        BooleanToEngStr(Data->GetResolveSymlinks()), BooleanToEngStr(Data->GetFollowDirectorySymlinks()));
      ADF("LS: %s, Ign LS warn: %s, Scp1 Comp: %s",
        Data->GetListingCommand(),
        BooleanToEngStr(Data->GetIgnoreLsWarnings()),
        BooleanToEngStr(Data->GetScp1Compatibility()));
    }
    if ((Data->GetFSProtocol() == fsSFTP) || (Data->GetFSProtocol() == fsSFTPonly))
    {
      UnicodeString Bugs;
      for (intptr_t Index = 0; Index < SFTP_BUG_COUNT; ++Index)
      {
        AddToList(Bugs, EnumName(Data->GetSFTPBug(static_cast<TSftpBug>(Index)), AutoSwitchNames), L",");
      }
      ADF("SFTP Bugs: %s", Bugs);
      ADF("SFTP Server: %s", Data->GetSftpServer().IsEmpty() ? UnicodeString(L"default") : Data->GetSftpServer());
    }
    bool FtpsOn = false;
    if (Data->GetFSProtocol() == fsFTP)
    {
      ADF("UTF: %s", EnumName(Data->GetNotUtf(), NotAutoSwitchNames)); // duplicated in UsesSsh branch
      UnicodeString Ftps;
      switch (Data->GetFtps())
      {
      case ftpsImplicit:
        Ftps = L"Implicit TLS/SSL";
        FtpsOn = true;
        break;

      case ftpsExplicitSsl:
        Ftps = L"Explicit SSL/TLS";
        FtpsOn = true;
        break;

      case ftpsExplicitTls:
        Ftps = L"Explicit TLS/SSL";
        FtpsOn = true;
        break;

      default:
        DebugAssert(Data->GetFtps() == ftpsNone);
        Ftps = L"None";
        break;
      }
      // kind of hidden option, so do not reveal it unless it is set
      if (Data->GetFtpTransferActiveImmediately() != asAuto)
      {
        ADF("Transfer active immediately: %s", EnumName(Data->GetFtpTransferActiveImmediately(), AutoSwitchNames));
      }
      ADF("FTPS: %s [Client certificate: %s]",
        Ftps, LogSensitive(Data->GetTlsCertificateFile()));
      ADF("FTP: Passive: %s [Force IP: %s]; MLSD: %s [List all: %s]; HOST: %s",
        BooleanToEngStr(Data->GetFtpPasvMode()),
        EnumName(Data->GetFtpForcePasvIp(), AutoSwitchNames),
        EnumName(Data->GetFtpUseMlsd(), AutoSwitchNames),
        EnumName(Data->GetFtpListAll(), AutoSwitchNames),
        EnumName(Data->GetFtpHost(), AutoSwitchNames));
    }
    if (Data->GetFSProtocol() == fsWebDAV)
    {
      FtpsOn = (Data->GetFtps() != ftpsNone);
      ADF("HTTPS: %s [Client certificate: %s]",
        BooleanToEngStr(FtpsOn), LogSensitive(Data->GetTlsCertificateFile()));
    }
    if (FtpsOn)
    {
      if (Data->GetFSProtocol() == fsFTP)
      {
        ADF("Session reuse: %s", BooleanToEngStr(Data->GetSslSessionReuse()));
      }
      ADF("TLS/SSL versions: %s-%s", GetTlsVersionName(Data->GetMinTlsVersion()), GetTlsVersionName(Data->GetMaxTlsVersion()));
    }
    ADF("Local directory: %s, Remote directory: %s, Update: %s, Cache: %s",
      Data->GetLocalDirectory().IsEmpty() ? UnicodeString(L"default") : Data->GetLocalDirectory(),
      Data->GetRemoteDirectory().IsEmpty() ? UnicodeString(L"home") : Data->GetRemoteDirectory(),
      BooleanToEngStr(Data->GetUpdateDirectories()),
      BooleanToEngStr(Data->GetCacheDirectories()));
    ADF("Cache directory changes: %s, Permanent: %s",
      BooleanToEngStr(Data->GetCacheDirectoryChanges()),
      BooleanToEngStr(Data->GetPreserveDirectoryChanges()));
    ADF("Recycle bin: Delete to: %s, Overwritten to: %s, Bin path: %s",
      BooleanToEngStr(Data->GetDeleteToRecycleBin()),
      BooleanToEngStr(Data->GetOverwrittenToRecycleBin()),
      Data->GetRecycleBinPath());
    if (Data->GetTrimVMSVersions())
    {
      ADF("Trim VMS versions: %s",
        BooleanToEngStr(Data->GetTrimVMSVersions()));
    }
    UnicodeString TimeInfo;
    if ((Data->GetFSProtocol() == fsSFTP) || (Data->GetFSProtocol() == fsSFTPonly) || (Data->GetFSProtocol() == fsSCPonly) || (Data->GetFSProtocol() == fsWebDAV))
    {
      AddToList(TimeInfo, FORMAT(L"DST mode: %s", EnumName(ToInt(Data->GetDSTMode()), DSTModeNames)), L";");
    }
    if ((Data->GetFSProtocol() == fsSCPonly) || (Data->GetFSProtocol() == fsFTP))
    {
      intptr_t TimeDifferenceMin = TimeToMinutes(Data->GetTimeDifference());
      AddToList(TimeInfo, FORMAT(L"Timezone offset: %dh %dm", TimeDifferenceMin / MinsPerHour, TimeDifferenceMin % MinsPerHour), L";");
    }
    ADSTR(TimeInfo);

    if (Data->GetFSProtocol() == fsWebDAV)
    {
      ADF("Compression: %s",
        BooleanToEngStr(Data->GetCompression()));
    }

    AddSeparator();
  }
}
Example #19
0
void WINAPI SetStartupInfoW(const struct PluginStartupInfo * psi)
{
  DebugAssert(FarPlugin);
  TFarPluginGuard Guard;
  FarPlugin->SetStartupInfo(psi);
}
void TActionLog::Add(UnicodeString Line)
{
  DebugAssert(FConfiguration);
  if (FLogging)
  {
    TGuard Guard(FCriticalSection);
    if (FLogger == nullptr)
    {
      OpenLogFile();
    }

    if (FLogger != nullptr)
    {
      try
      {
        UTF8String UtfLine = UTF8String(Line);
        size_t Written =
          FLogger->Write(UtfLine.c_str(), UtfLine.Length());
        if (Written != static_cast<size_t>(UtfLine.Length()))
        {
          throw ECRTExtException(L"");
        }
        Written =
          FLogger->Write("\n", 1);
        if (Written != 1)
        {
          throw ECRTExtException(L"");
        }
      }
      catch (Exception &E)
      {
//        FCriticalSection.Release();

        // avoid endless loop when trying to close tags when closing log, when logging has failed
        if (!FFailed)
        {
          FFailed = true;
          // We failed logging, turn it off and notify user.
          FConfiguration->SetLogActions(false);
          if (FConfiguration->GetLogActionsRequired())
          {
            throw EFatal(&E, LoadStr(LOG_FATAL_ERROR));
          }
          else
          {
            try
            {
              throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
            }
            catch (Exception &E2)
            {
              if (FUI != nullptr)
              {
                FUI->HandleExtendedException(&E2);
              }
            }
          }
        }
      }
    }
  }
}
Example #21
0
void WINAPI GetPluginInfoW(PluginInfo * pi)
{
  DebugAssert(FarPlugin);
  TFarPluginGuard Guard;
  FarPlugin->GetPluginInfo(pi);
}
 void Rollback(Exception *E)
 {
   DebugAssert(FErrorMessages == nullptr);
   FErrorMessages = ExceptionToMoreMessages(E);
   Close(RolledBack);
 }
Example #23
0
BaseIndex::Iterator BaseIndex::upper_bound(const std::vector<AllTypeVariant>& values) const {
  DebugAssert((_get_indexed_segments().size() >= values.size()),
              "BaseIndex: The number of queried segments has to be less or equal to the number of indexed segments.");

  return _upper_bound(values);
}
 inline void Close(TState State)
 {
   DebugAssert(FState == Opened);
   FState = State;
   FLog->RecordPendingActions();
 }
Example #25
0
//---------------------------------------------------------------------------
void __fastcall TKeyGenerator::SetKeyType(TKeyType value)
{
  DebugAssert(FState != kgGenerating);
  FState = kgInitializing;
  FKeyType = value;
}
TSessionLog::~TSessionLog()
{
  FClosed = true;
  ReflectSettings();
  DebugAssert(FLogger == nullptr);
}
Example #27
0
//---------------------------------------------------------------------------
AnsiString __fastcall TKeyGenerator::GetAuthorizedKeysLine()
{
  DebugAssert(FSSH2Key);
  return FORMAT("%s %s %s", (FSSH2Key->alg->name, PublicKey, Comment));
}
void TSessionLog::DoAddToParent(TLogLineType Type, UnicodeString ALine)
{
  DebugAssert(FParent != nullptr);
  FParent->Add(Type, ALine);
}
Example #29
0
Bool DiffZipFiles(const CDynamicFilenameSet &arFiles, const Filename &fnNew, const Filename &fnDestZip, const char* pchPassword)
{
	AutoAlloc <ZipFile> pOldZip, pNewZip, pDiffZip;
	ZipArray arStrings;
	ZipFileInfo info;
	String strName;
	Bool bExisted;
	Bool bOK = false;
	Int32 l, lCount;
	ZipArrayEntry* pEntry;
	void* pchData = nullptr;
	UInt32 lMaxDataLen = 0;
	ZipWriteInfo writeinfo;
	Bool bAppFolderChanged = false;

	if (!pOldZip || !pNewZip || !pDiffZip)
		return false;

	if (!pNewZip->Open(fnNew, true) || !pDiffZip->Open(fnDestZip, false))
		return false;

	// first, add all files of the new zip file into our array
	if (pNewZip->GoToFirstFile())
	{
		do
		{
			if (!pNewZip->GetCurrentFileInfo(info) ||
					!pNewZip->GetCurrentFileInfo(&strName))
				GOTO_ERROR;

			ZipArrayEntry* pEntry = arStrings.SearchObject(&strName);
			if (!pEntry)
			{
				pEntry = NewObjClear(ZipArrayEntry);
				if (!pEntry)
					GOTO_ERROR;
				pEntry->strName = strName;
				pEntry->bInNew = true;
				pEntry->bInOld = false;
				pEntry->ulCRCNew = info.lCRC32;
				pEntry->lNewSize = info.lUncompressedSize;
				pEntry->bChanged = false;
				pEntry->bInAppFolder = strName.FindFirst(".app/", nullptr);
				arStrings.InsertObject(pEntry, bExisted);
				DebugAssert(!bExisted);
			}
			else
			{
				// exists twice?!
				DebugAssert(false);
			}
		} while (pNewZip->GoToNextFile());
	}

	// browse through the array and check if something has changed
	for (l = 0; l < arFiles.GetElementCount(); l++)
	{
		if (!pOldZip->Open(*arFiles[l], true))
			GOTO_ERROR;
		if (pOldZip->GoToFirstFile())
		{
			do
			{
				if (!pOldZip->GetCurrentFileInfo(info) ||
						!pOldZip->GetCurrentFileInfo(&strName))
					GOTO_ERROR;

				ZipArrayEntry* pEntry = arStrings.SearchObject(&strName);
				if (!pEntry)
				{
					// file has been deleted
					pEntry = NewObjClear(ZipArrayEntry);
					if (!pEntry)
						GOTO_ERROR;
						pEntry->strName = strName;
					pEntry->bInNew = false;
					pEntry->bInOld = true;
					arStrings.InsertObject(pEntry, bExisted);
					DebugAssert(!bExisted);
				}
				else
				{
					// check for size and CRC
					pEntry->bInOld++;
					if ((pEntry->lNewSize != info.lUncompressedSize || pEntry->ulCRCNew != info.lCRC32) && pEntry->bInNew)
					{
						pEntry->bChanged = true;
						if (pEntry->bInAppFolder)
							bAppFolderChanged = true;
					}
				}
			} while (pOldZip->GoToNextFile());
		}
		pOldZip->Close();
	}

	lCount = arFiles.GetElementCount();
	for (l = 0; l < arStrings.GetElementCount(); l++)
	{
		if (arStrings[l]->bInNew)
			// we want to add it - mark as old if it exists in all old archives
			arStrings[l]->bInOld = (arStrings[l]->bInOld == lCount);
		else
			// old if it exists in at least one archive
			arStrings[l]->bInOld = (arStrings[l]->bInOld > 0);
	}

	lCount = arStrings.GetElementCount();
	if (!bAppFolderChanged)
	{
		// check if a new file as been added
		for (l = 0; l < lCount; l++)
		{
			pEntry = arStrings.GetObjectAt(l);
			if (!pEntry)
			{
				DebugAssert(false);
				continue;
			}
			if (pEntry->bInAppFolder && pEntry->bInNew && !pEntry->bInOld)
			{
				bAppFolderChanged = true;
				break;
			}
		}
	}

	for (l = 0; l < lCount; l++)
	{
		pEntry = arStrings.GetObjectAt(l);
		if (!pEntry)
		{
			DebugAssert(false);
			continue;
		}
		if (pEntry->bChanged || (pEntry->bInNew && !pEntry->bInOld) || (bAppFolderChanged && pEntry->bInAppFolder))
		{
			// the file has changed or was added, copy it from the new distri to the diff
			if (!pNewZip->LocateFile(pEntry->strName))
				GOTO_ERROR;
			if (!pNewZip->GetCurrentFileInfo(info))
				GOTO_ERROR;
			if (!pchData || lMaxDataLen < pEntry->lNewSize)
			{
				DeleteMem(pchData);
				pchData = NewMem(UChar, pEntry->lNewSize + 1);
				if (!pchData)
					GOTO_ERROR;
				lMaxDataLen = pEntry->lNewSize;
			}

			if (!pNewZip->OpenCurrentFile(pchPassword))
				GOTO_ERROR;

			if (pNewZip->ReadCurrentFile(pchData, pEntry->lNewSize) != pEntry->lNewSize)
				GOTO_ERROR;

			pNewZip->CloseCurrentFile();

			writeinfo.ti = info.t;
			if (pEntry->strName[pEntry->strName.GetLength() - 1] == '/')
			{
				writeinfo.lExternalAttr = ZIP_FLAG_DIRECTORY;
				writeinfo.lInternalAttr = 0;
				if (!pDiffZip->CreateFileInZip(pEntry->strName, &writeinfo, nullptr, 0, nullptr, 0, nullptr, ZipMethodStore, 0, pchPassword, 0))
					GOTO_ERROR;
				if (!pDiffZip->CloseFileInZip())
					GOTO_ERROR;
			}
			else
			{
				writeinfo.lExternalAttr = info.lExternalAttr;
				writeinfo.lInternalAttr = info.lInternalAttr;
				if (!pDiffZip->CreateFileInZip(pEntry->strName, &writeinfo, nullptr, 0, nullptr, 0, nullptr, ZipMethodDeflate, 9, nullptr, 0))
					GOTO_ERROR;
				if (!pDiffZip->WriteInFileInZip(pchData, pEntry->lNewSize))
					GOTO_ERROR;
				if (!pDiffZip->CloseFileInZip())
					GOTO_ERROR;
			}
		}
		else if (!pEntry->bInNew && pEntry->bInOld)
		{
			if (pEntry->strName[pEntry->strName.GetLength() - 1] == '/')
			{
				writeinfo.lExternalAttr = ZIP_FLAG_DIRECTORY;
				writeinfo.lInternalAttr = 0;
				if (!pDiffZip->CreateFileInZip("----" + pEntry->strName, &writeinfo, nullptr, 0, nullptr, 0, nullptr, ZipMethodStore, 0, pchPassword, 0))
					GOTO_ERROR;
				if (!pDiffZip->CloseFileInZip())
					GOTO_ERROR;
			}
			else
			{
				writeinfo.lExternalAttr = 0;
				writeinfo.lInternalAttr = 0;
				if (!pDiffZip->CreateFileInZip("----" + pEntry->strName, &writeinfo, nullptr, 0, nullptr, 0, nullptr, ZipMethodStore, 9, nullptr, 0))
					GOTO_ERROR;
				if (!pDiffZip->CloseFileInZip())
					GOTO_ERROR;
			}
		}
	}

	bOK = true;
error:
	pOldZip->Close();
	pNewZip->Close();
	pDiffZip->Close();

	arStrings.Free();
	DeleteMem(pchData);
	return bOK;
}
const WChar * String::ScanVAW( const WChar * inStr, const WChar * strFormat, VArgPtr pArgList ) const
{
    Bool bUnsigned;

    while( *strFormat != WNULLBYTE ) {
        if ( *strFormat != WTEXT('%') ) {
            if ( *inStr != *strFormat )
                break;
            ++inStr; ++strFormat;
            continue;
        }
        ++strFormat;

        if ( *strFormat == WTEXT('%') ) {
            if ( *inStr != *strFormat )
                break;
            ++inStr; ++strFormat;
            continue;
        }

        bUnsigned = false;
        if ( *strFormat == WTEXT('u') || *strFormat == WTEXT('U') ) {
            bUnsigned = true;
            ++strFormat;
        }

        switch( *strFormat ) {
            case WTEXT('s'): case WTEXT('S'): {
                    WChar * outString = VArg_Get( pArgList, WChar* );
                    UInt iLength = VArg_Get( pArgList, UInt );
                    NCopyW( outString, inStr, iLength );
                    inStr += iLength;
                } break;
            case WTEXT('f'): {
                    Float * outFloat = VArg_Get( pArgList, Float* );
                    *outFloat = ToFloatW( inStr, &inStr );
                } break;
            case WTEXT('F'): {
                    Double * outDouble = VArg_Get( pArgList, Double* );
                    *outDouble = ToDoubleW( inStr, &inStr );
                } break;
            case WTEXT('n'): {
                    if ( bUnsigned ) {
                        UInt * outUInt = VArg_Get( pArgList, UInt* );
                        *outUInt = (UInt)ToUIntW( inStr, &inStr );
                    } else {
                        Int * outInt = VArg_Get( pArgList, Int* );
                        *outInt = (Int)ToIntW( inStr, &inStr );
                    }
                } break;
            case WTEXT('N'): {
                    if ( bUnsigned ) {
                        UInt64 * outUInt64 = VArg_Get( pArgList, UInt64* );
                        *outUInt64 = ToUIntW( inStr, &inStr );
                    } else {
                        Int64 * outInt64 = VArg_Get( pArgList, Int64* );
                        *outInt64 = ToIntW( inStr, &inStr );
                    }
                } break;
            default: DebugAssert( false ); break;
        }