// stroke_input.jp
// Sunabe kazumichi 2009
// http://dp48069596.lolipop.jp/
//

function onInit() {
	count=0;
	content=thewordTextedit.text;	
	div="";
	splitter="words";
	refreshText();
 	setIdleEventInterval(1);
	pSpacing=true;
	pStroke=true;
	OVer=false; 
	oldJust=0;
	// place to create text before moving it.
	tP=new Point(-8000,-8000);
	}
	
function onMouseDown(event){
// Stroke Layer set
	aDoc=activeDocument;
	aLayer=aDoc.activeLayer;	
	if(!(aLayer.name=="Stroke")){
	var aLayer=new Layer();
	aLayer.activate();
	aLayer.name="Stroke";
	}
//	
	var fontSize=parseInt(theFontSizeField.text);
	var fontFam="SDstroke-latin";
	var fontWeight="latin";
	var fontTracking=theFontTrackingField.text;

	fSt=new CharacterStyle();
	fSt.font = fonts[fontFam][fontWeight];
	fSt.fontSize = fontSize;
	fSt.tracking=fontTracking;
	pos=event.point;
	oldPos=pos;
	text=new PointText(tP);	
	text.characterStyle=fSt;	
	text.content=content[count];	
	if (OVer==true){
		text.orientation=1;
		}else{
			text.orientation=0;
		}	
	nText=text.clone();
	nText.characterStyle=fSt;	
	maxHor=0;
	maxVer=0;
	
	cl=content.length;
	
	if(splitter=="letters"){
		maxVer=fontSize+fontSize*fontTracking/1000; //*0.8 Latin
	}else{
		maxVer=fontSize+fontSize*fontTracking/1000;
	}	
}

function onMouseUp(event){		
	text.remove();
	nText.remove();
	wordsList.get(count).selected=true;	
	StrokeText();
}

function onMouseDrag(event){
	rpCnt=0;
	pos=event.point;
	dist=pos.subtract(oldPos);
	var absDist=new Point(Math.abs(dist.x),Math.abs(dist.y))
	if(absDist.x>=maxHor | absDist.y>=maxVer){
		count++;
		var hDir=dist.x/absDist.x;
		if(isNaN(hDir)) hDir=1;
		var vDir=dist.y/absDist.y;
		if(isNaN(vDir)) vDir=1;		
		if(count>=cl)	count=0;
		if(pSpacing){
			var tPoint=new Point(oldPos.x+Math.min(absDist.x,maxHor)*hDir,oldPos.y+Math.min(absDist.y,maxVer)*vDir);
		}else{
			var tPoint=pos;
		}
		nText.translate(tPoint.subtract(tP));       
		if(maxHor<=absDist.x && dist.x<0){
			//align the text to the right
			nText.paragraphStyle.justification=1;
			//if its the first character with right justification,
			//move it to the right by the amount of it's own width
			if(oldJust==0){
				offset=new Point(text.bounds.width,0);
				}				
				nText.translate(offset);							
			oldJust=1;
		}else{
			oldJust=0;
		}
		maxHor=text.bounds.width;
		oldPos=tPoint;		
		text.content=content[count];				
		nText=text.clone();
		if(typeof nText != Path) nText.characterStyle=fSt;			
	}				
}

function StrokeText(){	
	bkColor = new CMYKColor(0,0,0,1);	
	aDoc=activeDocument;
	sdLayer=aDoc.activeLayer;
	var sel = sdLayer.items
	if (sel.length > 0) {	
		for (var j = 0; j < sel.length; j++) {		
		var	apath = sel[j];	
		apath.selected=true;
		}
	}					
	OutlineText();
	Closeoff();		
}

function OutlineText(){	
	gpath=new Array();
	allObjects = document.getMatchingItems(PointText, { selected: true });		
	countOfObjects = allObjects.length;	 
	for (var j = 0; j < countOfObjects; j++)
	{
	var chspath = allObjects[j].characterStyle;

	if(chspath.font.name=="latin"){
	gpath.push(allObjects[j]);	
	}

	try {
		gpath[j].createOutline(); 
	 	gpath[j].remove();		
	 }
	 catch(e){};
	 }		
}

function Closeoff(){	
	aDoc=activeDocument;
	sdLayer=aDoc.activeLayer;
	var sel = sdLayer.items;
	if (sel.length > 0) {	
		for (var j = 0; j < sel.length; j++) {
		
			if (sel[j] instanceof Path){	
			var	apath = sel[j];
	
			apath.closed = false;
			apath.style.fill.color = null;
			apath.style.stroke.width = 0;
			apath.style.stroke.color =  bkColor;
			apath.selected=true;
			}		
		}		 	 
	}	
}

function refreshText(){
	if(splitter=="letters"){
		content=thewordTextedit.text;
		div="";
	}else{
		content=thewordTextedit.text.replace(/\r/g," ");
		content=content.replace(/ /g," ||");
		content=content.split("||");  
		div=" ";	
	}
	count=0;
	resetwordsList();
}

function resetwordsList(){
	wordsList.removeAll();
	wordsList.add(content[0]).selected = true;
	var cl=content.length;
	for(i=1; cl>i; i++){
		wordsList.add(content[i]);
	}
}

function drawCurves(art){
	var l = art.children.length;
	if(l){
		for(var i=0; i<l; i++){
			drawCurves(art.children[i])
		}
	}else{
		var curveL = art.curves.length;
		for (var i= 0; i< curveL; i++){
			var curve = art.curves[i];
		drawCurve(curve);
		}
	}
}

function drawCurve(curve){
	var pt1 = curve.point1;
	var pt2 = curve.point2;
	var handle1 = curve.handle1.add(pt1);
	var handle2 = curve.handle2.add(pt2);
	
	var tangent = new Path();
	tangent.moveTo(pt1);
	tangent.curveTo(handle1,handle2,pt2);
}

function createTangent(pt,pt2,strokeColor,strokeWidth){
	var tangent = new Path();
	tangent.segments.add(pt);
	tangent.segments.add(pt2);
	tangent.style.stroke.width=strokeWidth;
	tangent.style.stroke.color=strokeColor;
	tangent.style.fill.color=null;
	return tangent;
}

function dbug(msg)
{if (true)
		print('::debug: '+msg);
}

// ------------------------  Dialog stuff  ------------------------ 

var dialog = new FloatingDialog(FloatingDialog.OPTION_TABBED);
	dialog.setTitle("Stroke Input");

var pMenu=dialog.popupMenu;

var popLetters = new ListEntry(pMenu){
	text:"Draw letters",

	onSelect:function(){
		if(splitter!="letters"){
			splitter="letters";
			refreshText();	
		}
		popWords.checked=false;
		popLetters.checked=true;
	}
}

var popWords = new ListEntry(pMenu){
	text:"Draw words",
		
	onSelect:function(){
		if(splitter!="words"){
			splitter="words";
			refreshText();	
		}	
		popWords.checked=true;
		popLetters.checked=false;
	}
}

var popSep = new ListEntry(pMenu){
	seperator:true
}

var popPerfect = new ListEntry(pMenu){
	text:"Perfect spacing",
	checked:true,
	onSelect:function(){
		if(popPerfect.checked){
			pSpacing=false;
			popPerfect.checked=false;
		}else{
			pSpacing=true;
			popPerfect.checked=true;
		}
	}
}

pMenu.visible=true;

var thewordTextedit = new TextEdit(dialog,TextEdit.OPTION_MULTILINE){
	bounds:[8, 13, 200, 3*20],  //
	text:"Input Words"
};
			// button one
		var OhorRadio = new RadioButton(dialog);
		OhorRadio.setChecked(true);
		OhorRadio.setPosition(107, 80);
		OhorRadio.setSize(20, 15);
		OhorRadio.onClick = function(){ 
			OVer= false;
		}		
			// button two
		var OVerRadio = new RadioButton(dialog);
		OVerRadio.setPosition(107, 100);
		OVerRadio.setSize(20, 15);
		OVerRadio.onClick = function(){
			OVer= true; 			
		}
			//text for radiobutton 1
		var OrientRadioText1 = new Static(dialog);
		OrientRadioText1.setText("Orientation_Hor.");
		OrientRadioText1.setSize(OrientRadioText1.bestSize);
		OrientRadioText1.setPosition(10, 80);
		
			//text for radiobutton 2
		var OrientRadioText2 = new Static(dialog);
		OrientRadioText2.setText("Orientation_Ver.");
		OrientRadioText2.setSize(OrientRadioText2.bestSize);
		OrientRadioText2.setPosition(10, 100);
		
		// ----- end radiobuttons -----
		
var thewordButton = new Button(dialog){
	text:"Refresh",
	position:new Point(145,80),
	onClick:function(){
		refreshText();
	}
};
	thewordButton.setSize(60,20);

var wordsList = new PopupList(dialog){
	text:"Words List",
	bounds:[10, 122, 100, 20],
	onDraw:function(){
		if(wordsList.length>0) count=wordsList.activeEntry.index;
	}
};

var theFontSize = new Static(dialog){
	text:"Size:",
	position:new Point(145, 110)
};
	theFontSize.setSize(theFontSize.bestSize);


var theFontSizeField = new TextEdit(dialog){
	bounds: [177, 110, 25, 20],
	text:"42"
};

var theFontTracking = new Static(dialog){
	text:"Tracking:",
	position: new Point(120, 130)
};
	theFontTracking.setSize([theFontTracking.bestSize.width-11,theFontTracking.bestSize.height]);

var theFontTrackingField = new TextEdit(dialog){
	bounds:[177, 130, 25, 20],
	text:"0"
};



var linealizeButton = new Button(dialog){
	text:"Linealize",
	position:new Point(10,162),
	onClick : function(){	
		paths = [];
	aDoc=activeDocument;
	sdLayer=aDoc.activeLayer;

	var selItems = sdLayer.items
	var selLen = selItems.length;
	for(var i=0; i<selLen; i++){
		var art = selItems[i];				
	if (art  instanceof Path && art.selected==true){	
		paths.push(art);	
		}	
	}	
	var bpath = new Path();	
	// concatenate smoothed paths
		for(var i = 0; i < paths.length; i++) {
		bpath.segments.addAll(paths[i].segments);
		paths[i].remove();
	}	
	}
};
	linealizeButton.setSize(60,20);

var unsegButton = new Button(dialog){
	text:"Un-seg.",
	position:new Point(77,162),
	onClick : function(){	
	
	var selItems =document.getMatchingItems(Path, { selected: true });
	var selLen = selItems.length;
	for(var i=0; i<selLen; i++){
		var art = selItems[i];
		drawCurves(art)
		art.remove();
		}
	}
};
	unsegButton.setSize(60,20);
	
var reverseButton = new Button(dialog){
	text:"Reverse",
	position:new Point(145,162),
	onClick : function(){
		//
		var revpath = document.getMatchingItems(Path, { selected: true });
		for (var j = 0; j < revpath.length; j++)
		{
		try {	
		 revpath[j].reverse(); 
		 }
			 catch(e){};
	}
	}
};
reverseButton.setSize(60,20);

//Length division selection
var lengthButton = new Button(dialog){
	text:"Length",
	position:new Point(10,206),
	onClick : function(){
	
		var fontSize=parseInt(theFontSizeField.text);
		var art = new Path();			
		len1Color = new CMYKColor(0,1,1,1/100);	
		len2Color = new CMYKColor(0,1,1,2/100);		
		len3Color = new CMYKColor(0,1,1,3/100);		
		len4Color = new CMYKColor(0,1,1,4/100);	
		len5Color = new CMYKColor(0,1,1,5/100);	
		len6Color = new CMYKColor(0,1,1,6/100);	
	
		var shapes =  activeDocument.getMatchingItems(Path, {selected: true});	
		for (var j = 0; j < shapes.length; j++) 			
	{			
	var shape = shapes[j];	
//	print('::shape.length::: '+shape.length);		
//un-CompoundPath
	if(shape.parent instanceof CompoundPath){
		var alertMessage =  'PLEASE !! \n\nUN-Group(Ctrl+Shift+G), \nUN-CompoundPath(Ctrl+Shift+Alt+8)';
		var dialog = new PopupDialog();
		dialog.alert(alertMessage);
	break;
	}	
	var plen = shape.length;
			var len=Math.round(plen*fontSize/420)     
	var art=shape
			switch(len)
			{
			case 0: art.style.stroke.color=len1Color;break;
			case 1: art.style.stroke.color=len1Color;break;
			case 2: art.style.stroke.color=len2Color;break;
			case 3:art.style.stroke.color=len3Color;break;
			case 4: art.style.stroke.color=len4Color;break;
			case 5: art.style.stroke.color=len5Color; break;
			default:art.style.stroke.color=len6Color; break;
			}
		}	
	}
};
	lengthButton.setSize(60,20);

//Ver- Hor-  Slant division selection
var verhorButton = new Button(dialog){
	text:"ver-hor Line",
	position:new Point(108,206),
	onClick : function(){	

//tangent init ----------------------------------
	var tan1=0.1;
	var tan2=10;
//-------------------------------------
	var vl, hl, tn, sl1, sl2 ,sl3;
	var shape = new Path();
			
		vlColor = new CMYKColor(1,1,0,1/100);	
		hlColor = new CMYKColor(1,1,0,2/100);		
		sl1Color = new CMYKColor(1,1,0,3/100);		
		sl2Color = new CMYKColor(1,1,0,4/100);	
		sl3Color = new CMYKColor(1,1,0,5/100);	
		var shapes =  activeDocument.getMatchingItems(Path, {selected: true});	
		for (var j = 0; j < shapes.length; j++) 
	{			
		 shape = shapes[j];
//un-CompoundPath
	if(shape.parent instanceof CompoundPath){
		var alertMessage =  'PLEASE !! \n\nUN-Group(Ctrl+Shift+G), \nUN-CompoundPath(Ctrl+Shift+Alt+8)';
		var dialog = new PopupDialog();
		dialog.alert(alertMessage);
	break;
	}	
	if (!(shape.bounds.width==0)){ tn=shape.bounds.height/shape.bounds.width;}
	if (shape.bounds.width==0 ) {vl=true;shape.style.stroke.color=vlColor}
	else if (shape.bounds.height==0) {hl=true; shape.style.stroke.color=hlColor;}
	else if (0<tn && tn<tan1){hl=true;shape.style.stroke.color=hlColor; }   
	else if (0>tn && tn>-tan1){hl=true;shape.style.stroke.color=hlColor; }   
	else if (tan2<tn) {vl=true; shape.style.stroke.color=vlColor; }  
	else if (-tan2>tn ) {vl=true; shape.style.stroke.color=vlColor; }    
	else if (tan2>tn && tn>tan1) {sl1=true; shape.style.stroke.color=sl1Color; }
	else if (-tan2<tn && tn<-tan1) {sl2=true;shape.style.stroke.color=sl2Color;}
	tn=0; 
	hl= vl=sl= sl2=false;
		}	
	}
};
verhorButton.setSize(80,20);

var thewordFrame=new Frame(dialog){
	text:"Text",
	size:[210,150],
	position: new Point(3,0)
};

var pathFrame=new Frame(dialog){
	text:"Path",
	size:[210,40],
	position:new Point(3, 147)
};

var selectionFrame=new Frame(dialog){
	text:"Selection",
	size:[210,40],
	position:new Point(3, 190)
};

dialog.setSize(216, 234);
dialog.setVisible(true);
dialog.onClose = function() {
        this.destroy();
};

