﻿function 开启事件监听() {
    
try
{
    arg_num = arguments.length;
}
catch(e)
{
    arguments = []; //初始赋值为空
}

eventName = "set";

//开启监听
enable_notifier(eventName, $.fileName);
alert("开启成功")
//取消监听
//disable_notifier(eventName, $.fileName);

//这里进行监控调用事件
if (arguments.length >= 2) 
{
    //alert(arguments.length);
//~     alert(arguments[0],"动作参数1"); //动作描述符 AR
//~     alert(arguments[1],"动作参数2"); //动作事件ID
    
    //alert("事件名:"+typeIDToStringID(arguments[1])+"\n"+"事件ID:"+arguments[1],"提示:");
    moveToGuideCenter();
    //main(arguments[0], arguments[1]);  
}

function moveToGuideCenter() {
    if (app.documents.length === 0 || !app.activeDocument.selection.bounds) {
        alert("没有打开的文档或没有有效的选区。");
        return;
    }

    var doc = app.activeDocument;
    var guides = doc.guides;
    var xGuide = null;
    var yGuide = null;

    // 找到 X 方向和 Y 方向上的参考线
    for (var i = 0; i < guides.length; i++) {
        var guide = guides[i];
        if (guide.direction === Direction.HORIZONTAL && yGuide === null) {
            yGuide = guide;
        } else if (guide.direction === Direction.VERTICAL && xGuide === null) {
            xGuide = guide;
        }
    }

    if (xGuide === null || yGuide === null) {
        alert("必须确保存在一条水平和一条垂直参考线。");
        return;
    }

    var intersectionX = xGuide.coordinate;
    var intersectionY = yGuide.coordinate;

    var bounds = doc.selection.bounds;
    var xCenter = bounds[0] + (bounds[2] - bounds[0]) / 2;
    var yCenter = bounds[1] + (bounds[3] - bounds[1]) / 2;

    var deltaX = intersectionX - xCenter;
    var deltaY = intersectionY - yCenter;

    // 取消当前选区
    doc.selection.deselect();

    // 移动选区图层
    var selectedLayer = doc.activeLayer;
    selectedLayer.translate(deltaX, deltaY);
}





function enable_notifier(event_name, script_name, event_class)  
{  
try   
    {  
    for (var i = 0; i < app.notifiers.length; i++)  
        {  
        if (app.notifiers[i].event == event_name &&  
            File(app.notifiers[i].eventFile).fsName.toLowerCase() == File(script_name).fsName.toLowerCase())  
            {  
            if (!app.notifiersEnabled) app.notifiersEnabled = true;  
            return true;  
            }  
        }  

    app.notifiers.add(event_name, File(script_name), event_class);  
    app.notifiersEnabled = true;  
    return true;  
    }  
catch (e) { _alert(e); return false; }  
}  
  

function disable_notifier(event_name, script_name, event_class)  
{  
try   
    {  
    var ret = false;  

    for (var i = 0; i < app.notifiers.length; i++)  
        {  
        if (app.notifiers[i].event == event_name &&  
            File(app.notifiers[i].eventFile).fsName.toLowerCase() == File(script_name).fsName.toLowerCase())  
            {  
            app.notifiers[i].remove();  
            ret = true;  
            }  
        }  

    if (!app.notifiers.length) app.notifiersEnabled = false;  

    return ret;  
    }  
catch (e) { _alert(e); return false; }  
}  
}  