/*
  Copyright © 2024 Takamaru <https://ss1.xrea.com/tkmr.s322.xrea.com/text-splitter/>

  Script Name: TextSplitter_v1.0.0.jsx
  
  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

#target photoshop

var userUnit = preferences.rulerUnits;
preferences.rulerUnits = Units.PIXELS;

var BR = String.fromCharCode(13);

function SplitMultiLine() {
}

SplitMultiLine.prototype.execute = function() {
    var docRef = app.activeDocument;
    var targetLayer = docRef.activeLayer;
    var originalText = targetLayer.textItem.contents;
    var textContents = originalText;

    // テキストが一行の場合は1文字ずつ改行する
    if (textContents.indexOf("\r") === -1) {
        var newTextContents = "";
        for (var i = 0; i < textContents.length; i++) {
            newTextContents += textContents.charAt(i) + "\r";
        }
        textContents = newTextContents;
        targetLayer.textItem.contents = textContents;
    }

    // 改行文字でテキストを分割
    var elems = textContents.split(BR);

    for (var i = 0; i < elems.length; i++) {
        if (elems[i] == "") {
            continue;
        }
        var newObj = targetLayer.duplicate();
        newObj.name = '';
        newObj.textItem.contents = elems[i];
    }

    // テキストが改行された場合のみ元のテキストを置き換える
    if (textContents !== originalText) {
        targetLayer.textItem.contents = originalText;
    }

    this.__destructor();
};

SplitMultiLine.prototype.__destructor = function() {
    preferences.rulerUnits = userUnit;
};

SplitMultiLine.prototype.__exit = function(msg) {
    if (msg) {
        alert(msg);
    }
    this.__destructor();
};

var oSplitMultiLine = new SplitMultiLine();
oSplitMultiLine.execute();
delete oSplitMultiLine;