シェルフの内容で右クリックマーキングメニューを変更

シェルフボタンのpopupMenuからCommandの登録
Alt + Shift マーキングメニュー
Ctrl + Alt + Shift マーキングメニュー
多々変更有り、ファイル名等
```kohaku_markingMenu.mel
{ // global variable
    global string $gKohaku_MM_shelfMenuItemString;
    $gKohaku_MM_shelfMenuItemString = "";
    global string $gKohaku_MM_shelfSubMenuItemStringArray[];
    clear $gKohaku_MM_shelfSubMenuItemStringArray;
    global string $gKohaku_MM_shelfMenuMainShelf;
    $gKohaku_MM_shelfMenuMainShelf = "";
    global string $gKohaku_MM_shelfMenuSubShelfArray[];
    clear $gKohaku_MM_shelfMenuSubShelfArray;
    global string $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray[]; // abbreviation : 略語
    $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray = {
            ""
            , "U"
            , "D"
            , "LRU"
            , "LRD"
            , "L"
            , "R"
            , "C"
            , "A"
            , "S"
            , "CA"
            , "CS"
            , "AS"
            , "CAS"
            , "PA"
            , "PZ"
            , "PX"
            , "CU"
            , "CD"
            , "CLRU"
            , "CLRD"
            , "CL"
            , "CR"
            , "CPA"
            , "CPZ"
            , "CPX"
            , "SU"
            , "SD"
            , "SLRU"
            , "SLRD"
            , "SL"
            , "SR"
            , "SPA"
            , "SPZ"
            , "SPX"
            , "CSU"
            , "CSD"
            , "CSLRU"
            , "CSLRD"
            , "CSL"
            , "CSR"
            , "CSPA"
            , "CSPZ"
            , "CSPX"
            , "ASU"
            , "ASD"
            , "ASLRU"
            , "ASLRD"
            , "ASL"
            , "ASR"
            , "ASPA"
            , "ASPZ"
            , "ASPX"
            , "CASU"
            , "CASD"
            , "CASLRU"
            , "CASLRD"
            , "CASL"
            , "CASR"
            , "CASPA"
            , "CASPZ"
            , "CASPX"
        };
    global string $gKohaku_MM_eixitMarkingMenuCmdLabelArray[];
    $gKohaku_MM_eixitMarkingMenuCmdLabelArray = {
            "None"
            , "exit marking menu by mouse scroll \"U\"p"
            , "exit marking menu by mouse scroll \"D\"own"
            , "exit marking menu holding \"L\"eft + \"R\"ight mouse button by mouse scoll \"U\"p"
            , "exit marking menu holding \"L\"eft + \"R\"ight mouse button by mouse scoll \"D\"own"
            , "exit marking menu holding \"L\"eft mouse button"
            , "exit marking menu holding \"R\"ight mouse button"
            , "exit marking menu holding \"C\"trl key"
            , "exit marking menu holding \"A\"lt key"
            , "exit marking menu holding \"S\"hift key"
            , "exit marking menu holding \"C\"trl + \"A\"lt key"
            , "exit marking menu holding \"C\"trl + \"S\"hift key"
            , "exit marking menu holding \"A\"lt + \"S\"hift key"
            , "exit marking menu holding \"C\"trl + \"A\"lt + \"S\"hift key"
            , "exit marking menu by \"P\"ress \"A\" key"
            , "exit marking menu by \"P\"ress \"Z\" key"
            , "exit marking menu by \"P\"ress \"X\" key"
            , "exit \"C\"trl marking menu by mouse scroll \"U\"p"
            , "exit \"C\"trl marking menu by mouse scroll \"D\"own"
            , "exit \"C\"trl marking menu holding \"L\"eft + \"R\"ight mouse button by mouse scoll \"U\"p"
            , "exit \"C\"trl marking menu holding \"L\"eft + \"R\"ight mouse button by mouse scoll \"D\"own"
            , "exit \"C\"trl marking menu holding \"L\"eft mouse button"
            , "exit \"C\"trl marking menu holding \"R\"ight mouse button"
            , "exit \"C\"trl marking menu by \"P\"ress \"A\" key"
            , "exit \"C\"trl marking menu by \"P\"ress \"Z\" key"
            , "exit \"C\"trl marking menu by \"P\"ress \"X\" key"
            , "exit \"S\"hift marking menu by mouse scroll \"U\"p"
            , "exit \"S\"hift marking menu by mouse scroll \"D\"own"
            , "exit \"S\"hift marking menu holding \"L\"eft and \"R\"ight mouse button by mouse scoll \"U\"p"
            , "exit \"S\"hift marking menu holding \"L\"eft and \"R\"ight mouse button by mouse scoll \"D\"own"
            , "exit \"S\"hift marking menu holding \"L\"eft mouse button"
            , "exit \"S\"hift marking menu holding \"R\"ight mouse button"
            , "exit \"S\"hift marking menu by \"P\"ress \"A\" key"
            , "exit \"S\"hift marking menu by \"P\"ress \"Z\" key"
            , "exit \"S\"hift marking menu by \"P\"ress \"X\" key"
            , "exit \"C\"trl + \"S\"hift marking menu by mouse scroll \"U\"p"
            , "exit \"C\"trl + \"S\"hift marking menu by mouse scroll \"D\"own"
            , "exit \"C\"trl + \"S\"hift marking menu holding \"L\"eft and \"R\"ight mouse button by mouse scoll \"U\"p"
            , "exit \"C\"trl + \"S\"hift marking menu holding \"L\"eft and \"R\"ight mouse button by mouse scoll \"D\"own"
            , "exit \"C\"trl + \"S\"hift marking menu holding \"L\"eft mouse button"
            , "exit \"C\"trl + \"S\"hift marking menu holding \"R\"ight mouse button"
            , "exit \"C\"trl + \"S\"hift marking menu by \"P\"ress \"A\" key"
            , "exit \"C\"trl + \"S\"hift marking menu by \"P\"ress \"Z\" key"
            , "exit \"C\"trl + \"S\"hift marking menu by \"P\"ress \"X\" key"
            , "exit \"A\"lt + \"S\"hift marking menu by mouse scoll \"U\"p"
            , "exit \"A\"lt + \"S\"hift marking menu by mouse scoll \"D\"own"
            , "exit \"A\"lt + \"S\"hift marking menu holding \"L\"eft and \"R\"ight mouse button by mouse scoll \"U\"p"
            , "exit \"A\"lt + \"S\"hift marking menu holding \"L\"eft and \"R\"ight mouse button by mouse scoll \"D\"own"
            , "exit \"A\"lt + \"S\"hift marking menu holding \"L\"eft mouse button"
            , "exit \"A\"lt + \"S\"hift marking menu holding \"R\"ight mouse button"
            , "exit \"A\"lt + \"S\"hift marking menu by \"P\"ress \"A\" key"
            , "exit \"A\"lt + \"S\"hift marking menu by \"P\"ress \"Z\" key"
            , "exit \"A\"lt + \"S\"hift marking menu by \"P\"ress \"X\" key"
            , "exit \"C\"trl + \"A\"lt + \"S\"hift marking menu by mouse scroll \"U\"p"
            , "exit \"C\"trl + \"A\"lt + \"S\"hift marking menu by mouse scroll \"D\"own"
            , "exit \"C\"trl + \"A\"lt + \"S\"hift marking menu holding \"L\"eft and \"R\"ight mouse button by mouse scoll \"U\"p"
            , "exit \"C\"trl + \"A\"lt + \"S\"hift marking menu holding \"L\"eft and \"R\"ight mouse button by mouse scoll \"D\"own"
            , "exit \"C\"trl + \"A\"lt + \"S\"hift marking menu holding \"L\"eft mouse button"
            , "exit \"C\"trl + \"A\"lt + \"S\"hift marking menu holding \"R\"ight mouse button"
            , "exit \"C\"trl \"A\"lt + \"S\"hift marking menu by \"P\"ress \"A\" key"
            , "exit \"C\"trl \"A\"lt + \"S\"hift marking menu by \"P\"ress \"Z\" key"
            , "exit \"C\"trl \"A\"lt + \"S\"hift marking menu by \"P\"ress \"X\" key"
            };
    { // Eixit Marking Menu Command Array
        global string $gKohaku_MM_eixitMarkingMenuShelfButtonArray[];
        for($i = 0; $i < size($gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray); $i++){
            appendStringArray($gKohaku_MM_eixitMarkingMenuShelfButtonArray, {""}, 1);
        }
    }
    global int $gKohaku_MM_wheelAngleDelta;
    $gKohaku_MM_wheelAngleDelta = 0;
    global string $gKohaku_MM_pressedInMarkingMenukey; // key pressed in marking menu
    $gKohaku_MM_pressedInMarkingMenukey = "";
    global string $gKohaku_MM_selectedPrefs;
    $gKohaku_MM_selectedPrefs = "";
    global int $gKohaku_MM_rightClickScriptJobNum;
    global string $gKohaku_MM_collectNonSacredToolArray[];
    { // Python
        string $pythonCmd = "def kohaku_MM_createGlobalVariable():\n"
                          + "    try:\n"
                          + "        from PySide6.QtWidgets import QWidget\n"
                          + "        from shiboken6 import wrapInstance\n"
                          + "    except:\n"
                          + "        from PySide2.QtWidgets import QWidget\n"
                          + "        from shiboken2 import wrapInstance\n"
                          + "    from maya.OpenMayaUI import MQtUtil\n"
                          + "    ptr = MQtUtil.mainWindow()\n"
                          + "    global gKohaku_MM_mayaMainWindow\n" // MayaWindow
                          + "    gKohaku_MM_mayaMainWindow = wrapInstance(int(ptr), QWidget)\n"
                          + "kohaku_MM_createGlobalVariable()\n"
                          + "del kohaku_MM_createGlobalVariable"
                          ;
        python($pythonCmd);
    }
}
{ // Must be declared first (declared:宣言済み)
    // Initial G
    proc string kohaku_MM_local_getImageFromRunTimeCommand(string $runTimeCmd){
        if(!`runTimeCommand -exists $runTimeCmd`) return "";
        string $image;
        // CreatePlatonicSolidの場合にcatchQuiet必要
        catchQuiet($image = `runTimeCommand -image $runTimeCmd`);
        if($image != "") return $image;
        switch($runTimeCmd){
            case "CreatePlatonicSolid" :
                $image = "polyPlatonicSolid.png";
                break;
        }
        return $image;
    }
    proc string kohaku_MM_local_getRunTimeCmd(string $cmd){
        if(`runTimeCommand -exists $cmd`) return $cmd;
        { // For Context
            string $title;
            if(`contextInfo -exists $cmd`) $title = `contextInfo -query -title $cmd`;
            if($title != ""){ // There is a context without title (without:無し)
                $title = `substitute " " $title ""`;
                if(`runTimeCommand -exists $title`) return $title;
            }
        }
        { // performPolyExtrude 0 etc
            string $result;
            if(`gmatch $cmd "perform*"`){
                $result = `substitute "^perform" $cmd ""`;
                $result = `substitute " 0$" $result ""`;
            }
            if(`runTimeCommand -exists $result`) return $result;
        }
        string $runTimeCmd;
        switch($cmd){
            case "artSelectContext" :
                $runTimeCmd = "ArtPaintSelectTool";
                break;
            case "Harden Edge" :
                $runTimeCmd = "PolygonHardenEdge";
                break;
            case "performPolyBevel 3" :
                $runTimeCmd = "BevelPolygon";
                break;
            case "performPolyPrimitive PlatonicSolid 0" :
                $runTimeCmd = "CreatePlatonicSolid";
                break;
            case "polySlideEdgeContext" :
                $runTimeCmd = "SlideEdgeTool";
                break;
            case "polySelectEditContext" :
                $runTimeCmd = "DuplicateEdges";
                break;
            case "Soften Edge" :
                $runTimeCmd = "PolygonSoftenEdge";
                break;
        }
        return $runTimeCmd;
    }
}
// Initial B
proc string kohaku_MM_local_buildMenuItemString(string $shelfButton, int $mainMenuItemNum){
    string $menuItemString;
    if(`toolButton -ex $shelfButton`) return $menuItemString; // Tool button
    if(`separator -ex $shelfButton`){ // Separator
        $menuItemString += "menuItem -d true;\n";
        return $menuItemString;
    }
    string $targetPopUpMenu;
    int $subMenuFlg = false;
    { // shelfButtonにPopUpMenuがある場合
        string $popUpMenuToShelfButtonArray[] = `shelfButton -q -popupMenuArray $shelfButton`;
        for($popUpMenuToShelfButton in $popUpMenuToShelfButtonArray){
            if(`popupMenu -query -button $popUpMenuToShelfButton` == 3
                && !`popupMenu -query -altModifier $popUpMenuToShelfButton`
                && !`popupMenu -query -ctrlModifier $popUpMenuToShelfButton`
                && !`popupMenu -query -shiftModifier $popUpMenuToShelfButton`){
                    $targetPopUpMenu = $popUpMenuToShelfButton;
            }
        }
        if(`popupMenu -query -numberOfItems $targetPopUpMenu` > 4){
            string $label = `shelfButton -query -label $shelfButton` + " Etc";
            string $image = `shelfButton -query -image $shelfButton`;
            $menuItemString += "menuItem -label \"" + $label + "\" -image \"" + $image + "\" -subMenu on;\n";
            $subMenuFlg = true;
        }
    }
    string $radialPositionArray[] = {"N", "NW", "W", "SW", "S", "SE", "E", "NE"};
    int $radialPositionIndex = 0;
    { // Shelf Buttonからのメニュー
        string $cmdString = "shelfButton";
        string $radialPosition;
        if($subMenuFlg){
            $radialPosition = $radialPositionArray[$radialPositionIndex];
            $radialPositionIndex++;
        }
        $menuItemString += `kohaku_MM_local_buildMenuItemStringFromControl $cmdString $shelfButton $radialPosition`;
    }
    if($subMenuFlg){ // shelfButtonのPopUpMenuからのメニュー
        string $menuItemArray[] = `popupMenu -query -itemArray $targetPopUpMenu`;
        int $subSubMenuFlg = false;
        int $index = 0;
        for($menuItem in $menuItemArray){
            if(`menuItem -query -divider $menuItem`) break;
            string $radialPosition;
            if(size($radialPositionArray) > $radialPositionIndex && !`menuItem -query -isOptionBox $menuItem`){
                $radialPosition = $radialPositionArray[$radialPositionIndex];
                $radialPositionIndex++;
            }
            if($radialPosition == "" &&  !`menuItem -query -isOptionBox $menuItem`
                && !$subSubMenuFlg && $mainMenuItemNum <= 8){
                string $label = `menuItem -query -label $menuItem` + " Etc";
                $menuItemString += "menuItem -label \"" + $label + "\" -subMenu on;\n";
                $subSubMenuFlg = true;
            }
            string $cmdString = "menuItem";
            $menuItemString += `kohaku_MM_local_buildMenuItemStringFromControl $cmdString $menuItem $radialPosition`;
        }
        if($subSubMenuFlg) $menuItemString += "setParent -m ..;\n";
        $menuItemString += "setParent -m ..;\n";
    }
    return $menuItemString;
}
proc string kohaku_MM_local_buildMenuItemStringFromControl(string $cmdString, string $control, string $radialPosition){
    string $menuItemString;
    { // Option
        if($cmdString == "menuItem"){
            if(`menuItem -query -isOptionBox $control`){
                string $cmd = `menuItem -query -command $control`;
                $menuItemString += "menuItem -optionBox true -command \"" + `encodeString $cmd` + "\";\n";
                return $menuItemString;
            }
        }
    }
    $menuItemString = "menuItem\n";
    $menuItemString += "    -label \"" + `eval ($cmdString + " -query -label " + $control)` + "\"\n";
    string $cmd;
    { // Command
        $cmd = `eval ($cmdString + " -query -command " + $control)`;
        $cmd = `encodeString $cmd`;
        $menuItemString += "    -command \"" + $cmd + "\"\n";
        if(size(`match "^\/\\* Kohaku_MM_checkBox" $cmd`)){ // CheckBox
            // For comments starting with /* Kohaku_MM_checkBox
            // Example:
            // /* Kohaku_MM_checkBox
            // eval("isolateSelect -query -state `getPanel -withFocus`")
            // */
            $cmd = `match "^\/\\* Kohaku_MM_checkBox.+\\*\/" $cmd`;
            $cmd = `substitute "^\/\*.*Kohaku_MM_checkBox\\\\n" $cmd ""`;
            $cmd = `substitute "\\\\n\\*\/$" $cmd ""`;
            $menuItemString += " -checkBox `eval \"" + $cmd + "\"`";
        }
    }
    $menuItemString += "    -enableCommandRepeat " + `eval ($cmdString + " -query -enableCommandRepeat " + $control)` + "\n";
    string $image = `eval ($cmdString + " -query -image " + $control)`;
    if($image == ""){
        string $runTimeCmd = kohaku_MM_local_getRunTimeCmd($cmd);
        if($runTimeCmd != "") $image = `runTimeCommand -query -image $runTimeCmd`;
        if($image == "") $image = `kohaku_MM_local_getImageFromRunTimeCommand $runTimeCmd`;
    }
    $menuItemString += "    -image \"" + $image + "\"\n";
    if($radialPosition != "") $menuItemString += "    -radialPosition \"" + $radialPosition + "\"\n";
    $menuItemString += "    -sourceType \"" + `eval ($cmdString + " -query -sourceType " + $control)` + "\"\n";
    $menuItemString += "    ;\n"; // Close
    { // OptionBox
        if($cmdString == "shelfButton"){
            string $doubleClickCmd = `eval ($cmdString + " -query -doubleClickCommand " + $control)`;
            if($doubleClickCmd != ""){
                $menuItemString += "menuItem -optionBox true -command \"" + `encodeString $doubleClickCmd` + "\";\n";
            }
        }
    }
    return $menuItemString;
}
proc kohaku_MM_local_buildModelEditorPopupMenu(
    string $panelName, string $popupMenuName, string $postMenuCommand, int $buttonNum,
    int $altModifier, int $ctrlModifier, int $shiftModifier, int $markingMenu){
    string $panelControl = `modelEditor -query -control $panelName`;
    $popupMenuName = $panelName + $popupMenuName;
    if(`popupMenu -exists $popupMenuName`) deleteUI -menu $popupMenuName;
    string $popupMenu = `popupMenu -parent $panelControl $popupMenuName`;
    popupMenu -edit
        -altModifier $altModifier
        -button $buttonNum
        -ctrlModifier $ctrlModifier 
        -markingMenu $markingMenu
        -postMenuCommand $postMenuCommand
        -shiftModifier $shiftModifier
        $popupMenu
        ;
}

// Initial C
proc kohaku_MM_local_changeProc(string $proc, string $searchStringArray[], string $addStringArray[], string $positionFlgArray[]){
    string $result = `whatIs $proc`;
    if($result == "Mel procedure entered interactively.") return; // If modified (modified:修正済)
    string $procString;
    string $filePath = `substitute "^.+found in: " $result ""`;
    string $allLines[] = freadAllLines($filePath);
    int $flg = off;
    int $KakkohajimeNum = $kakkoTojiruNum = 0;
    for($line in $allLines){
        { // Get text
            if(`gmatch $line ("*global proc " + $proc + "*")`) $flg = on;
            if($flg){
                int $index = $positionFlg = 0;
                for($searchString in $searchStringArray){
                    if(`gmatch $line $searchString`){
                        if($positionFlgArray[$index] == "before"){
                            $procString += "\n" + $addStringArray[$index];
                        }
                        break;
                    }
                    $index++;
                }
                $procString += "\n" + $line;
                if($positionFlgArray[$index] == "after") $procString += "\n" + $addStringArray[$index]; // Add later (later:後)
                if(`gmatch $line "}*"`) break;
            }
        }
    }
    eval($procString);
}
proc int kohaku_MM_local_countermeasureToolButton(string $shelfButton, string $targetShelf, int $targetShelfIndex){ // Measures:対策
    int $toolButtonFlg = `toolButton -ex $shelfButton`;
    if($toolButtonFlg){
        deleteUI -ctl $shelfButton;
        if(`shelfLayout -q -nch $targetShelf` == 0){ // 空の状態を維持
            saveShelf $targetShelf (`internalVar -ush` + "shelf_" + $targetShelf);
            string $shelfFileNum = "shelfFile" + $targetShelfIndex;
            optionVar -stringValue $shelfFileNum "0"; // 重要
        }
    }
    return $toolButtonFlg;
}
// Initial D
proc kohaku_MM_local_deselectExitMarkingMenuCmd(string $targetShelfButton){
    string $targetImageOverlayLabel = `shelfButton -query -imageOverlayLabel $targetShelfButton`;
    { // ImageOverlayLabel
        string $shelfButtonArray[] = `shelfLayout -q -ca "Kohaku_ExitMarkingMenuCommand"`;
        for($shelfButton in $shelfButtonArray){
            string $imageOverlayLabel = `shelfButton -q -imageOverlayLabel $shelfButton`;
            if($imageOverlayLabel == $targetImageOverlayLabel){
                shelfButton -edit -imageOverlayLabel "" $shelfButton;
                break;
            }
        }
    }
}
// Initial F
proc kohaku_MM_local_fixesContextPolyToolsMM(string $targetProc){
    string $result = `whatIs $targetProc`;
    if($result == "Mel procedure entered interactively.") return; // 修正済みの場合
    string $procString;
    string $filePath = `substitute "^.+found in: " $result ""`;
    string $allLines[] = freadAllLines($filePath);
    int $flg = off;
    for($line in $allLines){
        { // Exclude unnecessary setParent (Exclude:除く, unnecessary:不要)
            if(`gmatch $line "*-subMenu*"`) $flg = on;
            else if(`gmatch $line "*setParent*"`){
                if($flg) $flg = off;
                else continue;
            }
            $procString += $line + "\n";
        }
    }
    eval($procString);
}
// Initial G
proc string kohaku_MM_local_getAncestor(string $parent, int $numNumberOfGenerations){ // ancestor:祖先
    string $tokenizeArray[];
    tokenize $parent "|" $tokenizeArray;
    return $tokenizeArray[`size $tokenizeArray` - $numNumberOfGenerations];
}
proc string kohaku_MM_local_getCtxIcon(string $ctx){
    if(!`contextInfo -exists $ctx`) return "";
    string $title = `contextInfo -title $ctx`;
    $title = `substitute " " $title ""`;
    string $image;
    if(`runTimeCommand -exists $title`) $image = `runTimeCommand -query -image $title`;
    if($image == ""){
        switch($ctx){
            case "selectSuperContext":
                $image = "aselect.png";
                break;
            case "lassoSelectContext":
                $image = "lassoSelect.png";
                break;
            case "artSelectContext":
                $image = "artSelect.png";
                break;
            default :
                $image = `contextInfo -image1 $ctx`;
                break;
        }
    }
    return $image;
}
proc string kohaku_MM_local_getLabel(string $runTimeCmd){
    if($runTimeCmd == "") return "";
    string $label;
    { // ランタイムコマンドにラベルが有る場合
        if(`runTimeCommand -q -ex $runTimeCmd`){
            $label = `runTimeCommand -q -l $runTimeCmd`;
            if($label != "") return $label;
        }
    }
    switch($runTimeCmd){
        case "SelectTool" :
            $label = `uiRes("m_defaultRunTimeCommands.kEnableSelectToolLbl")`;
            break;
        case "LassoTool" :
            $label = `uiRes("s_HtoolStrings.rLassoToolName")`;
            break;
        case "ArtPaintSelectTool" :
            $label = `uiRes("m_dagMenuProc.kPaintSelect")`;
            break;
    }
    return $label;
}
proc int[] Kohaku_MM_local_getScreenSize(){
    string $cmd = "try:\n"
                + "    from PySide6.QtGui import QGuiApplication, QCursor\n"
                + "except:\n"
                + "    from PySide2.QtGui import QGuiApplication, QCursor\n"
                + "def getScreenSize():\n"
                + "    screen = QGuiApplication.screenAt(QCursor.pos())\n"
                + "    return [screen.availableSize().width(), screen.availableSize().height()]"
                ;
    python($cmd);        
    return python("getScreenSize()");
}
// Initial K
proc kohaku_MM_local_killRightClickScriptJob(string $menuItem){
    global int $gKohaku_MM_rightClickScriptJobNum;
    string $cmd = "if(`scriptJob -exists " + $gKohaku_MM_rightClickScriptJobNum + "`)"
                + " scriptJob -kill " + $gKohaku_MM_rightClickScriptJobNum;
    if(`menuItem -q -sm $menuItem`){
        string $originPmc = `menuItem -q -pmc $menuItem`;
        menuItem -e -pmc ($cmd + ";" + $originPmc) $menuItem;
    }else{
        string $originCmd = `menuItem -q -c $menuItem`;
        string $evalOriginCmd = "evalDeferred -en \"" + `encodeString $originCmd` + "\"";
        int $ecr = `menuItem -q -ecr $menuItem`;
        if($ecr){ // 最近のコマンドに入る場合
            menuItem -e -ecr false $menuItem;
            string $label = `menuItem -q -l $menuItem`;
            string $repeatLastCmd = "repeatLast -ac \"" + `encodeString $originCmd` + "\""
                                    + " -acl \"" + $label + "\"";
            $repeatLastCmd = "eval -ue false \"" + `encodeString $repeatLastCmd` + "\"";
            $evalOriginCmd += ";" + $repeatLastCmd;
        }
        $cmd = "eval -ue false \"" + $cmd + "\"";
        menuItem -e -c ($cmd + ";" + $evalOriginCmd) $menuItem;
    }
}
// Initial M
proc kohaku_MM_local_markingPrefs(string $prefs){
    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
    string $originPrefsShelfButton, $prefsShelfButton;
    global string $gKohaku_MM_selectedPrefs;
    for($shelfButton in $shelfButtonArray){
        string $shelfButtonLabel = `shelfButton -query -label $shelfButton`;
        if($shelfButtonLabel == ("Kohaku Marking Menu Prefs_" + $prefs)) $prefsShelfButton = $shelfButton;
        if($shelfButtonLabel == ("Kohaku Marking Menu Prefs_" + $gKohaku_MM_selectedPrefs)){
            $originPrefsShelfButton = $shelfButton;
        }
    }
    string $cmd = "try:\n"
                + "    from PySide6.QtCore import QEvent, QObject, Qt\n"
                + "    from PySide6.QtGui import QPainter, QPen\n"
                + "    from shiboken6 import wrapInstance\n"
                + "except:\n"
                + "    from PySide2.QtCore import QEvent, QObject, Qt\n"
                + "    from PySide2.QtGui import QPainter, QPen\n"
                + "class Kohaku_MM_shelfButtonEventFilter(QObject):\n"
                + "    def eventFilter(self, watched: QObject, event: QEvent):\n"
                + "        if event.type() == QEvent.Paint:\n"
                + "            painter = QPainter(watched)\n"
                + "            pen = QPen(Qt.gray, 2)\n"
                + "            painter.setPen(pen)\n"
                + "            painter.drawRect(watched.rect().adjusted(1, 1, -1, -1))\n"
                + "        return False\n"



                // 変数が存在する場合の処理



                + "gKohaku_MM_shelfButtonEventFilter = Kohaku_MM_shelfButtonEventFilter()\n"
                ;
    python($cmd);
    global string $gKohaku_MM_selectedPrefs;
    if($gKohaku_MM_selectedPrefs != "" && $gKohaku_MM_selectedPrefs != $prefs){
        $cmd = "try:\n"
                    + "    from PySide6.QtWidgets import QPushButton\n"
                    + "    from shiboken6 import wrapInstance\n"
                    + "except:\n"
                    + "    from PySide2.QtWidgets import QPushButton\n"
                    + "    from shiboken2 import wrapInstance\n"
                    + "from maya.OpenMayaUI import MQtUtil\n"
                    + "def kohaku_MM_removeShelfButtonEventFilter():\n"
                    + "    ptr = MQtUtil.findControl(\"" + $originPrefsShelfButton + "\")\n"
                    + "    pushButton = wrapInstance(int(ptr), QPushButton)\n"
                    + "    pushButton.removeEventFilter(gKohaku_MM_shelfButtonEventFilter)\n"
                    + "    pushButton.update()\n"
                    + "kohaku_MM_removeShelfButtonEventFilter()"
                    ;
        python($cmd);
    }
    $cmd = "try:\n"
                + "    from PySide6.QtWidgets import QPushButton\n"
                + "    from shiboken6 import wrapInstance\n"
                + "except:\n"
                + "    from PySide2.QtWidgets import QPushButton\n"
                + "    from shiboken2 import wrapInstance\n"
                + "from maya.OpenMayaUI import MQtUtil\n"
                + "def kohaku_MM_installShelfButtonEventFilter():\n"
                + "    ptr = MQtUtil.findControl(\"" + $prefsShelfButton + "\")\n"
                + "    pushButton = wrapInstance(int(ptr), QPushButton)\n"
                + "    pushButton.installEventFilter(gKohaku_MM_shelfButtonEventFilter)\n"
                + "    pushButton.update()\n"
                + "kohaku_MM_installShelfButtonEventFilter()"
                ;
    python($cmd);
}
// Initial R
proc kohaku_MM_local_registerExitMarkingMenuCommandimageOverlayLabel(string $targetShelfButton, string $newImageOverlayLabel){
    // Delete imageOverlayLabel, duplicate consideration (consideration:考慮)
    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
    for($shelfButton in $shelfButtonArray){
        if(`separator -exists $shelfButton`) continue; // Separator
        if(`toolButton -exists $shelfButton`) continue; // Tool Button
        string $imageOverlayLabel = `shelfButton -query -imageOverlayLabel $shelfButton`;
        if($imageOverlayLabel == $newImageOverlayLabel){
            shelfButton -edit -imageOverlayLabel "" $shelfButton;
        }
    }
    shelfButton -edit -imageOverlayLabel $newImageOverlayLabel $targetShelfButton;
}
proc kohaku_MM_local_registerExitMarkingMenuCommandComponent(string $shelfButton, string $imageOverlayLabel){
    if($imageOverlayLabel == "Prefs") return;
    global string $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray[];
    global string $gKohaku_MM_eixitMarkingMenuShelfButtonArray[];
    { // 元の登録を消去
        string $originImageOverlayLabel = `shelfButton -query -imageOverlayLabel $shelfButton`;
        if($originImageOverlayLabel != ""){
            int $index = stringArrayFind($originImageOverlayLabel, 0, $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray);
            if($index != -1) $gKohaku_MM_eixitMarkingMenuShelfButtonArray[$index] = "";
        }
    }
    { // 登録
        int $index = stringArrayFind($imageOverlayLabel, 0, $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray);
        if($index != -1) $gKohaku_MM_eixitMarkingMenuShelfButtonArray[$index] = $shelfButton;
    }
    string $exitMarkingMenuCmdLabelWindow = "kohaku_MM_exitMarkingMenuCmdLabelWindow_" + $imageOverlayLabel;
    { // Exit Marking Menu Command Label Windowが無い場合
        if(!`window -exists $exitMarkingMenuCmdLabelWindow`){
            python("kohaku_MM_buildExitMarkingMenuCmdLabelWindow(\"" + $exitMarkingMenuCmdLabelWindow + "\")");
        }
    }
    { // 編集
        string $image = `shelfButton -query -image $shelfButton`;
        string $label = `shelfButton -query -label $shelfButton`;
        string $cmd = "kohaku_MM_editExitMarkingMenuCmdLabelWindow(\"" + $exitMarkingMenuCmdLabelWindow + "\", \""
                                                                       + $image + "\", \""
                                                                       + $label + "\")"
                                                                       ;
        python($cmd);
    }
}



proc Kohaku_MM_local_createKohakuExitMarkingMenuCommandShelf(){
    string $shelfName = "Kohaku_ExitMarkingMenuCommand";
    if(`shelfLayout -exists "Kohaku_ExitMarkingMenuCommand"`) return;
    addNewShelfTab $shelfName;
    string $shelfFullPathName = `shelfLayout -query -fullPathName $shelfName`;
    string $childArray[] = `shelfLayout -query -childArray $shelfName`;
    for($shelfButton in $childArray) deleteUI -control $shelfButton; // May exist when deleted and created
    setParent $shelfFullPathName;
    { // Kohaku Smart Clear Selection
        string $cmd = "if(size(`ls -selection`)){"
             +     "evalDeferred \"select -clear\";"
             + "}else if(size(`ls -hilite`)){"
             +     "evalDeferred \"SelectNone\";"
             + "}"
             ;
        $cmd = `encodeString $cmd`;
        shelfButton
            -label "Kohaku Smart Clear Selection"
            -command ("eval -undoEnabled false \"" + $cmd + "\"")
            -enableCommandRepeat false
            -image "commandButton.png"
            -imageOverlayLabel "R"
            ;
    }
    { // Complete Tool
        shelfButton
            -label "Complete Tool"
            -command "CompleteCurrentTool"
            -enableCommandRepeat false
            -image "commandButton.png"
            -imageOverlayLabel "L"
            ;
    }
    { // Kohaku Smart Delete
        string $cmd = "{"
             +     "string $selection[] = `ls -long -selection`;"
             +     "string $selectionType, $resultArray[];"
             +     "if(!size($selection)) $selectionType = \"NONE\";"
             +     "if($selectionType != \"NONE\"){"
             +         "$resultArray = `filterExpand -expand false -selectionMask 31 $selection`;"
             +         "if(size($resultArray)) $selectionType = \"vertex\";"
             +         "$resultArray = `filterExpand -expand false -selectionMask 32 $selection`;"
             +         "if(size($resultArray)) $selectionType += \"edge\";"
             +         "$resultArray = `filterExpand -expand false -selectionMask 34 $selection`;"
             +         "if(size($resultArray)) $selectionType += \"face\";"
             +         "$resultArray = `filterExpand -expand false -selectionMask 35 $selection`;"
             +         "if(size($resultArray)) $selectionType = \"uv\";"
             +         "if($selectionType == \"vertex\"){"
             +             "evalDeferred -en \"DeleteVertex\";"
             +         "}else if($selectionType == \"edge\"){"
             +             "evalDeferred -en \"DeleteEdge\";"
             +         "}else if($selectionType == \"uv\"){"
             +             "evalDeferred -en \"DeleteUVs\";"
             +         "}else if($selectionType == \"face\" || $selectionType == \"\"){"
             +             "evalDeferred -en \"Delete\";"
             +         "}"
             +     "}"
             + "}"
             ;
        $cmd = `encodeString $cmd`;
        shelfButton
            -label "Kohaku Smart Delete"
            -command ("eval -undoEnabled false \"" + $cmd + "\"")
            -enableCommandRepeat false
            -image "delete.png"
            -imageOverlayLabel "A"
            ;
    }
    { // Toggle Shelf
        shelfButton
            -label "Toggle Shelf"
            -command "ToggleShelf"
            -enableCommandRepeat false
            -image "commandButton.png"
            -imageOverlayLabel "LRU"
            ;
    }
    { // Kohaku Toggle Script Editor
        string $cmd = "if(!`workspaceControl -exists scriptEditorPanel1Window`){\n"
                    + "    ScriptEditor;\n"
                    + "}else{\n"
                    + "    workspaceControl -edit -visible true scriptEditorPanel1Window;\n"
                    + "    if(`workspaceControl -query -floating scriptEditorPanel1Window`){\n"
                    + "        workspaceControl -edit -close scriptEditorPanel1Window;\n"
                    + "    }else{\n"
                    + "        if(`workspaceControl -query -collapse scriptEditorPanel1Window`){\n"
                    + "            workspaceControl -edit -collapse false scriptEditorPanel1Window;\n"
                    + "        }else{\n"
                    + "            if(`workspaceControl -query -raise scriptEditorPanel1Window`){\n"
                    + "                workspaceControl -edit -collapse true scriptEditorPanel1Window;\n"
                    + "            }else workspaceControl -edit -restore scriptEditorPanel1Window; // Select Tab\n"
                    + "        }\n"
                    + "    }\n"
                    + "}"
                    ;
        shelfButton
            -label "Kohaku Toggle Script Editor"
            -command $cmd
            -enableCommandRepeat false
            -image "commandButton.png"
            -imageOverlayLabel "LRD"
            ;
    }
    { // Kohaku Toggle Script Editor
        string $cmd = "if \"gKohaku_MM_toggleNoModifierMakingMenuVisible\" in globals():\n"
                    + "    gKohaku_MM_toggleNoModifierMakingMenuVisible = not gKohaku_MM_toggleNoModifierMakingMenuVisible"
                    ;
        shelfButton
            -label "Kohaku Toggle Object Making Menu Visible"
            -command $cmd
            -enableCommandRepeat false
            -image "commandButton.png"
            -imageOverlayLabel "CAS"
            -sourceType "python"
            ;
    }
    saveShelf $shelfFullPathName (`internalVar -ush` + "shelf_" + $shelfName);
}
proc string Kohaku_MM_local_recordDefaultPrefsToShelfButton(){
    if(!`shelfLayout -exists "Kohaku_ExitMarkingMenuCommand"`) return "";
    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
    string $prefsShelfButton;
    for($shelfButton in $shelfButtonArray){
        string $label = `shelfButton -query -label $shelfButton`;
        if($label == "Kohaku Marking Menu Prefs"){
            $prefsShelfButton = $shelfButton;
            break;
        }
    }
    global string $gKohaku_MM_shelfMenuMainShelf;
    string $cmd = "$gKohaku_MM_shelfMenuMainShelf = \"" + $gKohaku_MM_shelfMenuMainShelf +"\";\n";
    global string $gKohaku_MM_shelfMenuSubShelfArray[];
    string $subShelfArrayString = stringArrayToString($gKohaku_MM_shelfMenuSubShelfArray, "\", \"");
    if($subShelfArrayString != ""){
        $cmd += "$gKohaku_MM_shelfMenuSubShelfArray = {\"" + $subShelfArrayString + "\"};\n";
    }else{
        $cmd += "clear $gKohaku_MM_shelfMenuSubShelfArray;\n";
    }
    { // gKohaku_MM_selectedPrefs
        global string $gKohaku_MM_selectedPrefs;
        if($gKohaku_MM_selectedPrefs != ""){
            int $selectedPrefsFlg = false;
            for($shelfButton in $shelfButtonArray){
                string $label = `shelfButton -query -label $shelfButton`;
                if($label == ("Kohaku Marking Menu Prefs_" + $gKohaku_MM_selectedPrefs)){
                    $selectedPrefsFlg = true;
                    break;
                }
            }
            if($selectedPrefsFlg == false) $gKohaku_MM_selectedPrefs = "";
        }
        $cmd += "$gKohaku_MM_selectedPrefs = \"" + $gKohaku_MM_selectedPrefs + "\";";
    }
    string $shelfButtonFullName;
    if($prefsShelfButton == ""){
        setParent `shelfLayout -query -fullPathName "Kohaku_ExitMarkingMenuCommand"`;
        $shelfButtonFullName = `shelfButton`;
        shelfButton
            -edit
            -label "Kohaku Marking Menu Prefs"
            -command $cmd
            -enable false
            -image "commandButton.png"
            -imageOverlayLabel "Prefs"
            $shelfButtonFullName
            ;
    }else{
        shelfButton -edit -command $cmd $prefsShelfButton;
        $shelfButtonFullName = $prefsShelfButton;
    }
    return $shelfButtonFullName;
}
// Global
// Initial E
global proc Kohaku_MM_executeExitMarkingMenuCommand(string $flg){
    int $modifiersNum = `getModifiers`;
    string $cmdAbbreviation;
    string $mouseButtons = python("kohaku_MM_getMouseButtons()");
    global int $gKohaku_MM_wheelAngleDelta;
    global string $gKohaku_MM_pressedInMarkingMenukey;
    if($flg == ""){
        if($gKohaku_MM_pressedInMarkingMenukey != ""){
            switch($gKohaku_MM_pressedInMarkingMenukey){
                case "A" :
                    // exit marking menu by "P"ress "A" key
                    $cmdAbbreviation = "PA";
                    break;
                case "Z" :
                    // exit marking menu by "P"ress "Z" key
                    $cmdAbbreviation = "PZ";
                    break;
                case "X" :
                    // exit marking menu by "P"ress "X" key
                    $cmdAbbreviation = "PX";
                    break;
            }
        }else if($mouseButtons == "MouseButton.LeftButton"){
            // exit marking menu holding "L"eft mouse button
            $cmdAbbreviation = "L";
        }else if($mouseButtons == "MouseButton.RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // "exit marking menu by mouse scroll "U"p
                $cmdAbbreviation = "U";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit marking menu by mouse scroll "D"own
                $cmdAbbreviation = "D";
            }else{
                // exit marking menu holding "R"ight mouse button
                $cmdAbbreviation = "R";
            }
        }else if($mouseButtons == "MouseButton.LeftButton|RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit marking menu holdingand "L"eft and "R"ight mouse button by mouse scoll "U"p
                $cmdAbbreviation = "LRU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit marking menu holding "L"eft and "R"ight mouse button by mouse scoll "D"own
                $cmdAbbreviation = "LRD";
            }
        }else{
            switch($modifiersNum){
                case 1 : // Shift
                    // exit marking menu holding "S"hift key
                    $cmdAbbreviation = "S";
                    break;
                case 4 : // Ctrl
                    // exit marking menu holding "C"trl key
                    $cmdAbbreviation = "C";
                    break;
                case 5 : // Ctrl + Shift
                    // exit marking menu holding "C"trl + "S"hift key
                    $cmdAbbreviation = "CS";
                    break;
                case 8 : // Alt
                    // exit marking menu holding "A"lt key
                    $cmdAbbreviation = "A";
                    break;
                case 9 : // Alt + Shift
                    // exit marking menu holding "A"lt + "S"hift key
                    $cmdAbbreviation = "AS";
                    break;
                case 12 : // Ctrl + Alt
                    // exit marking menu holding "C"trl + "A"lt key
                    $cmdAbbreviation = "CA";
                    break;
                case 13 : // Ctrl + Alt + Shift
                    // exit marking menu holding "C"trl + "A"lt + "S"hift key
                    $cmdAbbreviation = "CAS";
                    break;
            }
        }
    }else if($flg == "Ctrl"){
        if($gKohaku_MM_pressedInMarkingMenukey != ""){
            switch($gKohaku_MM_pressedInMarkingMenukey){
                case "A" :
                    // exit "C"trl marking menu by "P"ress "A" key
                    $cmdAbbreviation = "CPA";
                    break;
                case "Z" :
                    // exit "C"trl marking menu by "P"ress "Z" key
                    $cmdAbbreviation = "CPZ";
                    break;
                case "X" :
                    // exit "C"trl marking menu by "P"ress "X" key
                    $cmdAbbreviation = "CPX";
                    break;
            }
        }else if($mouseButtons == "MouseButton.LeftButton"){
            // exit "C"trl marking menu holding "L"eft mouse button
            $cmdAbbreviation = "CL";
        }else if($mouseButtons == "MouseButton.RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "C"trl marking menu by mouse scroll "U"p
                $cmdAbbreviation = "CU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "C"trl marking menu by mouse scroll "D"own
                $cmdAbbreviation = "CD";
            }else{
                // exit "C"trl marking menu holding "R"ight mouse button
                $cmdAbbreviation = "CR";
            }
        }else if($mouseButtons == "MouseButton.LeftButton|RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "C"trl marking menu holding "L"eft and "R"ight mouse button by mouse scoll "U"p
                $cmdAbbreviation = "CLRU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "C"trl marking menu holding "L"eft and "R"ight mouse button by mouse scoll "D"own
                $cmdAbbreviation = "CLRD";
            }
        }
    }else if($flg == "Shift"){
        if($gKohaku_MM_pressedInMarkingMenukey != ""){
            switch($gKohaku_MM_pressedInMarkingMenukey){
                case "A" :
                    // exit "S"hift marking menu by "P"ress "A" key
                    $cmdAbbreviation = "SPA";
                    break;
                case "Z" :
                    // exit "S"hift marking menu by "P"ress "Z" key
                    $cmdAbbreviation = "SPZ";
                    break;
                case "X" :
                    // exit "S"hift marking menu by "P"ress "X" key
                    $cmdAbbreviation = "SPX";
                    break;
            }
        }else if($mouseButtons == "MouseButton.LeftButton"){
            // exit "S"hift marking menu holding "L"eft mouse button
            $cmdAbbreviation = "SL";
        }else if($mouseButtons == "MouseButton.RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "S"hift marking menu by mouse scroll "U"p
                $cmdAbbreviation = "SU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "S"hift marking menu by mouse scroll "D"own
                $cmdAbbreviation = "SD";
            }else{
                // exit "S"hift marking menu holding "R"ight mouse button
                $cmdAbbreviation = "SR";
            }
        }else if($mouseButtons == "MouseButton.LeftButton|RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "S"hift marking menu holding "L"eft and "R"ight mouse button by mouse scoll "U"p
                $cmdAbbreviation = "SLRU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "S"hift marking menu holding "L"eft and "R"ight mouse button by mouse scoll "D"own
                $cmdAbbreviation = "SLRD";
            }
        }
    }else if($flg == "CtrlShift"){
        if($gKohaku_MM_pressedInMarkingMenukey != ""){
            switch($gKohaku_MM_pressedInMarkingMenukey){
                case "A" :
                    // exit "C"trl + "S"hift marking menu by "P"ress "A" key
                    $cmdAbbreviation = "CSPA";
                    break;
                case "Z" :
                    // exit "C"trl + "S"hift marking menu by "P"ress "Z" key
                    $cmdAbbreviation = "CSPZ";
                    break;
                case "X" :
                    // exit "C"trl + "S"hift marking menu by "P"ress "X" key
                    $cmdAbbreviation = "CSPX";
                    break;
            }
        }else if($mouseButtons == "MouseButton.LeftButton"){
                // exit "C"trl + "S"hift marking menu holding "L"eft mouse button
                $cmdAbbreviation = "CSL";
        }else if($mouseButtons == "MouseButton.RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "C"trl + "S"hift marking menu by mouse scroll "U"p
                $cmdAbbreviation = "CSU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "C"trl + "S"hift marking menu by mouse scroll "D"own
                $cmdAbbreviation = "CSD";
            }else{
                // exit "C"trl + "S"hift marking menu holding "R"ight mouse button
                $cmdAbbreviation = "CSR";
            }
        }else if($mouseButtons == "MouseButton.LeftButton|RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "C"trl + "S"hift marking menu holding "L"eft and "R"ight mouse button by mouse scoll "U"p
                $cmdAbbreviation = "CSLRU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "C"trl + "S"hift marking menu holding "L"eft and "R"ight mouse button by mouse scoll "D"own
                $cmdAbbreviation = "CSLRD";
            }
        }
    }else if($flg == "AltShift"){
        if($gKohaku_MM_pressedInMarkingMenukey != ""){
            switch($gKohaku_MM_pressedInMarkingMenukey){
                case "A" :
                    // exit "A"lt + "S"hift marking menu by "P"ress "A" key
                    $cmdAbbreviation = "ASPA";
                    break;
                case "Z" :
                    // exit "A"lt + "S"hift marking menu by "P"ress "Z" key
                    $cmdAbbreviation = "ASPZ";
                    break;
                case "X" :
                    // exit "A"lt + "S"hift marking menu by "P"ress "X" key
                    $cmdAbbreviation = "ASPX";
                    break;
            }
        }else if($mouseButtons == "MouseButton.LeftButton"){
            // exit "A"lt + "S"hift marking menu holding "L"eft mouse button
            $cmdAbbreviation = "ASL";
        }else if($mouseButtons == "MouseButton.RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "A"lt + "S"hift marking menu by mouse scoll "U"p
                $cmdAbbreviation = "ASU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "A"lt + "S"hift marking menu by mouse scoll "D"own
                $cmdAbbreviation = "ASD";
            }else{
                // exit "A"lt + "S"hift marking menu holding "R"ight mouse button
                $cmdAbbreviation = "ASR";
            }
        }else if($mouseButtons == "MouseButton.LeftButton|RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "A"lt + "S"hift marking menu holding "L"eft and "R"ight mouse button by mouse scoll "U"p
                $cmdAbbreviation = "ASLRU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "A"lt + "S"hift marking menu holding "L"eft and "R"ight mouse button by mouse scoll "D"own
                $cmdAbbreviation = "ASLRD";
            }
        }
    }else if($flg == "CtrlAltShift"){
        if($gKohaku_MM_pressedInMarkingMenukey != ""){
            switch($gKohaku_MM_pressedInMarkingMenukey){
                case "A" :
                    // exit "C"trl "A"lt + "S"hift marking menu by "P"ress "A" key
                    $cmdAbbreviation = "CASPA";
                    break;
                case "Z" :
                    // exit "C"trl "A"lt + "S"hift marking menu by "P"ress "Z" key
                    $cmdAbbreviation = "CASPZ";
                    break;
                case "X" :
                    // exit "C"trl "A"lt + "S"hift marking menu by "P"ress "X" key
                    $cmdAbbreviation = "CASPX";
                    break;
            }
        }else if($mouseButtons == "MouseButton.LeftButton"){
                // exit "C"trl + "A"lt + "S"hift marking menu holding "L"eft mouse button
                $cmdAbbreviation = "CASL";
        }else if($mouseButtons == "MouseButton.RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "C"trl + "A"lt + "S"hift marking menu by mouse scroll "U"p
                $cmdAbbreviation = "CASU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "C"trl + "A"lt + "S"hift marking menu by mouse scroll "D"own
                $cmdAbbreviation = "CASD";
            }else{
                // exit "C"trl + "A"lt + "S"hift marking menu holding "R"ight mouse button
                $cmdAbbreviation = "CASR";
            }
        }else if($mouseButtons == "MouseButton.LeftButton|RightButton"){
            if($gKohaku_MM_wheelAngleDelta > 0){
                // exit "C"trl + "A"lt + "S"hift marking menu holding "L"eft and "R"ight mouse button by mouse scoll "U"p
                $cmdAbbreviation = "CASLRU";
            }else if($gKohaku_MM_wheelAngleDelta < 0){
                // exit "C"trl + "A"lt + "S"hift marking menu holding "L"eft and "R"ight mouse button by mouse scoll "D"own
                $cmdAbbreviation = "CASLRD";
            }
        }
    }
    { // commandの実行と表示
        global string $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray[];
        global string $gKohaku_MM_eixitMarkingMenuShelfButtonArray[];
        int $index = stringArrayFind($cmdAbbreviation, 0, $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray);
        string $shelfButton = $gKohaku_MM_eixitMarkingMenuShelfButtonArray[$index];
        if($shelfButton == "") return;
        { // Echo
            string $label = `shelfButton -query -label $shelfButton`;
            string $proc = "Kohaku_MM_" + $cmdAbbreviation + "_Command";
            evalEcho ($proc + " \"" + $label + "\"");
        }
        { // Show Label
            string $exitMarkingMenuCmdLabelWindow = "kohaku_MM_exitMarkingMenuCmdLabelWindow_" + $cmdAbbreviation;
            python("kohaku_MM_showExitMarkingMenuCmdLabelWindow(\"" + $exitMarkingMenuCmdLabelWindow + "\")");
        }
        { //Execute
            string $cmd = `shelfButton -query -command $shelfButton`;
            string $sourceType = `shelfButton -query -sourceType $shelfButton`;
            if($sourceType == "python"){
                $cmd = "python(\"" + `encodeString $cmd` + "\")";
            }
            evalDeferred $cmd;
        }
    }
}
global proc Kohaku_MM_showTearOffMenu(string $QMenu, string $parent){
    string $cmd = "try:\n"
                + "    from PySide6.QtWidgets import QMenu, QMenuBar\n"
                + "    from PySide6.QtGui import QCursor\n"
                + "    from shiboken6 import wrapInstance\n"
                + "except:\n"
                + "    from PySide2.QtWidgets import QMenu\n"
                + "    from PySide2.QtGui import QCursor\n"
                + "    from shiboken2 import wrapInstance\n"
                + "from maya.OpenMayaUI import MQtUtil\n"
                + "from maya import mel\n"
                + "def showTearOffMenu():\n"
                + "    ptr = MQtUtil.findControl(\"" + $QMenu + "\")\n"
                + "    widget = wrapInstance(int(ptr), QMenu)\n"
                + "    widget.showTearOffMenu(QCursor.pos())\n"
                // TearOffされたメニューはTearOff元のメニューの兄弟として追加されるのでそれを取得
                + "    ptr = MQtUtil.findControl(\"" + $parent + "\")\n"
                + "    widget = wrapInstance(int(ptr), QMenuBar)\n"
                + "    children = widget.findChildren(QMenu)\n"
                + "    tearOffMenu = children[-1]\n"
                + "    newPosArray = mel.eval(\"Kohaku_MM_positionAdjustment(\"\n"
                + "                          + str(QCursor.pos().x()) + \", \"\n"
                + "                          + str(QCursor.pos().y()) + \", \"\n"
                + "                          + str(tearOffMenu.frameSize().width() + 10) + \", \"\n"
                + "                          + str(tearOffMenu.frameSize().height() + 10) + \")\"\n"
                + "                          )\n"
                + "    tearOffMenu.move(newPosArray[0], newPosArray[1])\n"
                + "    tearOffMenu.activateWindow()\n"
                + "showTearOffMenu()"
                ;
    python($cmd);
}
global proc int[] Kohaku_MM_positionAdjustment(
    int $widgetPosX, int $widgetPosY, int $widgetWidth, int $widgetHeight){
    int $screenSizeArray[] = Kohaku_MM_local_getScreenSize();
    int $screenWidth = $screenSizeArray[0];
    int $screenHeight = $screenSizeArray[1];
    int $newWidgetPosX = (($widgetPosX + $widgetWidth) > $screenWidth) ?
        ($widgetPosX - (($widgetPosX + $widgetWidth) - $screenWidth)) : $widgetPosX;
    int $newWidgetPosY = (($widgetPosY + $widgetHeight) > $screenHeight) ?
        ($widgetPosY - (($widgetPosY + $widgetHeight) - $screenHeight)) : $widgetPosY;
    return {$newWidgetPosX, $newWidgetPosY};
}
global proc Kohaku_MM_buildRegisterExitMarkingMenuCmdMenu(string $parent, string $shelfButton){
    popupMenu -edit -deleteAllItems $parent;
    setParent -menu $parent;
    radioMenuItemCollection;
    global string $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray[];
    global string $gKohaku_MM_eixitMarkingMenuCmdLabelArray[];
    for($abbreviation in $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray){
        int $index = stringArrayFind($abbreviation,0, $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray);
        string $label = ($abbreviation != "") ? ($abbreviation + " : ") : "";
        $label += $gKohaku_MM_eixitMarkingMenuCmdLabelArray[$index];
        string $imageOverlayLabel = `shelfButton -query -imageOverlayLabel $shelfButton`;
        int $radioButtonFlg = ($imageOverlayLabel == $abbreviation);
        string $cmd = "Kohaku_MM_registerExitMarkingMenuCmd("
                    + "\"" + $shelfButton + "\""
                    + ", \"" + $abbreviation + "\")"
                    ;
        global string $gKohaku_MM_selectedPrefs;
        if($gKohaku_MM_selectedPrefs != ""){
            $cmd += ";\nKohaku_MM_createOrUpdatePrefs(\"" + $gKohaku_MM_selectedPrefs + "\")";
        }
        menuItem
            -label $label
            -radioButton $radioButtonFlg
            -command $cmd
            -enableCommandRepeat false
            ;
    }
}
global proc Kohaku_MM_clearCVHullEp(){ 
    // When switching to an object mask with NurbsCurve, etc.,
    // if a point is selected along with the last selected object, deselect it
    string $selectionArray[] = `ls -l -sl`;
    string $tailSelectionArray[] = `ls -l -sl -tl 1`;
    { // If not NurbsCurve etc
        global int $gSelectNurbsCurvesBit, $gSelectNurbsSurfacesBit, $gSelectCurvesOnSurfacesBit;
        int $selectionMaskNumArray[] = {$gSelectNurbsCurvesBit, $gSelectNurbsSurfacesBit, $gSelectCurvesOnSurfacesBit};
        string $filterExpandSelectionArray[];
        for($selectionMask in $selectionMaskNumArray){
            $filterExpandSelectionArray = `filterExpand -ex false -fp true -sm $selectionMask $selectionArray`;
            if(size($filterExpandSelectionArray)) break;
        }
        if(!size($filterExpandSelectionArray)) return;
    }
    string $targetSelectionArray[];
    { // Points selected with the last object selected
        for($selection in $selectionArray){
            if(size(`match ($tailSelectionArray[0] + "\\.") $selection`)){ // For points
                appendStringArray($targetSelectionArray, {$selection}, 1);
            }
        }
    }
    if(size($targetSelectionArray)){
        string $newSelectionArray[] = stringArrayRemove($targetSelectionArray, $selectionArray);
        { // If the start and end points are the same in EP, exclude the end point number
            for($newSelection in $newSelectionArray){
                { // If not EP
                    global int $gSelectEditPointsBit;
                    $filterExpandSelectionArray = `filterExpand -ex false -fp true -sm $gSelectEditPointsBit {$newSelection}`;
                    if(!size($filterExpandSelectionArray)) continue;
                }
                $result = `match "^.+\\..+\\[" $newSelection`;
                float $coordinateArray[] = `getAttr ($result + "*]")`;
                int $size = size($coordinateArray);
                int $resultNum = stringArrayFind(($result + ($size / 3) + "]"), 0, $newSelectionArray);
                if($resultNum >= 0) stringArrayRemoveAtIndex($resultNum, $newSelectionArray);
            }
        }
        string $selectionString = stringArrayToString($newSelectionArray, "\", \"");
        $selectionString = "{\"" + $selectionString + "\"}";
        // In case of -d,the point where the starting point and the ending point are the same does not work
        evalDeferred ("select " + $selectionString);
    }
}
global proc Kohaku_MM_collectNonSacredTool(){
    global string $gKohaku_MM_collectNonSacredToolArray[];
    string $currentCtx = `currentCtx`;
    if($currentCtx == "ShowManips" || $currentCtx == "") return; // There is a case that you can't get it.
    string $sacredTool[] = {"selectSuperContext", "lassoSelectContext", "artSelectContext",
                    "moveSuperContext", "RotateSuperContext", "scaleSuperContext"};
    if(stringArrayContains($currentCtx, $sacredTool)) return;
    int $index = stringArrayFind($currentCtx, 0, $gKohaku_MM_collectNonSacredToolArray);
    stringArrayRemoveAtIndex($index, $gKohaku_MM_collectNonSacredToolArray);
    stringArrayInsertAtIndex(0, $gKohaku_MM_collectNonSacredToolArray, $currentCtx);
}
global proc Kohaku_MM_deleteMenuItemAndCreateSubMenu(string $parent, string $menuItemName, string $targetRpArray[] ,string $cmd, int $parentFlg){
    string $menuItemArray[] = `popupMenu -q -ia $parent`;
    if(!`size $menuItemArray`) return; // menuItem無し
    string $label;
    string $previousRp;
    for($menuItem in $menuItemArray){
        $menuItem = $parent + "|" + $menuItem;
        string $rp = `menuItem -q -rp $menuItem`;
        if($label == "" && $rp == "" && !`menuItem -q -isOptionBox $menuItem` && !`menuItem -q -d $menuItem`){
            $label = `menuItem -q -l $menuItem`;
        }
        if(`menuItem -q -ob $menuItem`){ // Option Box
            if(stringArrayContains($previousRp, $targetRpArray)) deleteUI -mi $menuItem;
        }else if(stringArrayContains($rp, $targetRpArray)) deleteUI -mi $menuItem;
        $previousRp = $rp;
    }
    if($label != "" && $cmd != ""){
        setParent -m $parent;
        $menuItemName = "Kohaku_MM_" + $menuItemName;
        if($parentFlg) $cmd += " \"" + $parent + "|" + $menuItemName + "\"";
        if(!`gmatch $label "* Etc"`) $label += " Etc";
        menuItem
            -l $label
            -sm on
            -pmc ($cmd + ";"
                + "Kohaku_MM_deleteMenuItemAndCreateSubMenu"
                + " \"" + $parent + "|" + $menuItemName + "\""
                + " \"\""
                + " {\"N\", \"NW\", \"W\", \"SW\",  \"S\", \"SE\", \"E\", \"NE\"}"
                + " \"\""
                + " " + $parentFlg)
            -pmo true
            $menuItemName
            ;
        setParent -m ..;
    }
}

global proc kohaku_MM_setExistMarkingMenuCommand(string $flg){
    global int $gKohaku_MM_wheelAngleDelta;
    $gKohaku_MM_wheelAngleDelta = 0;
    global string $gKohaku_MM_pressedInMarkingMenukey;
    $gKohaku_MM_pressedInMarkingMenukey = "";
    global int $gKohaku_MM_rightClickScriptJobNum;
    $gKohaku_MM_rightClickScriptJobNum = 
        `scriptJob -ro true -ie ("eval -ue false \"Kohaku_MM_executeExitMarkingMenuCommand(\\\"" + $flg + "\\\")\"")`;
}
global proc Kohaku_MM_radialPoint(string $parent){
    string $menuItemArray[] = `popupMenu -q -ia $parent`;
    int $index = 0;
    for($menuItem in $menuItemArray){
        $menuItem = $parent + "|" + $menuItem;
        string $radialPositionArray[] = {"N", "NW", "W", "SW", "S", "SE", "E", "NE"};
        string $rp = `menuItem -q -rp $menuItem`;
        if($rp == "" && !`menuItem -q -isOptionBox $menuItem` && !`menuItem -q -d $menuItem`){
            if(size($radialPositionArray) >= ($index + 1)){
                menuItem -e -rp $radialPositionArray[$index] $menuItem;
                $index++;
            }
        }
    }
}
global proc Kohaku_MM_registerExitMarkingMenuCmd(string $shelfButton, string $imageOverlayLabel){
    if($imageOverlayLabel != ""){
        kohaku_MM_local_registerExitMarkingMenuCommandComponent($shelfButton, $imageOverlayLabel);
        kohaku_MM_local_registerExitMarkingMenuCommandimageOverlayLabel($shelfButton, $imageOverlayLabel);

    }else{
        kohaku_MM_local_deselectExitMarkingMenuCmd($shelfButton);
    }
}
global proc Kohaku_MM_scriptEditorPop(){
    global string $gLastFocusedCommandExecuter;
    string $popupMenuArray[] = `cmdScrollFieldExecuter -q -pma $gLastFocusedCommandExecuter`;
    string $popupMenu;
    for($popupMenu in $popupMenuArray){
        if(`popupMenu -q -b $popupMenu` == 3 &&
            `popupMenu -q -alt $popupMenu` == off &&
            `popupMenu -q -ctl $popupMenu` == off &&
            `popupMenu -q -sh $popupMenu` == off) break;
        $popupMenu = "";
    }
    string $parent = $gLastFocusedCommandExecuter + "|" + $popupMenu;
    string $proc = "verifyCommandPopupMenus";
    { // Is the menu changed?
        string $addMenuItem = $parent + "|Kohaku_MM_" + $proc;
        if(`menuItem -ex $addMenuItem`){
            string $menuItemArray[] = `popupMenu -q -ia $addMenuItem`;
            string $label;
            string $targetLabel = `uiRes("m_scriptEditorPanel.kFile")`;
            for($menuItem in $menuItemArray){
                $menuItem = $addMenuItem + "|" + $menuItem;
                $label = `menuItem -q -l $menuItem`;
                if($label == $targetLabel) break;
            }
            global int $gScriptEditorMenuBarVisible;
            if($gScriptEditorMenuBarVisible){
                if($label != $targetLabel) return;
            }else{
                if($label == $targetLabel) return;
            }
        }
    }
    string $rpArray[] = {"N", "NW", "W", "SW", "S", "SE", "E", "NE", ""};
    string $cmd = "popupMenu -e -dai \"" + $parent + "|Kohaku_MM_" + $proc + "\";"
                + "buildScriptEditorCondensedPopupMenus(" // Proc to be executed when adding tabs
                + "\"" + $parent + "|Kohaku_MM_" + $proc + "\"" + ", false);"
                + "if (!$gScriptEditorMenuBarVisible) " // If there is no menu bar
                + "buildScriptEditorMenus(\"" + $parent + "|Kohaku_MM_" + $proc + "\""
                + ", \"" + `shortObjectName $gLastFocusedCommandExecuter` + "\", true, false)";
    Kohaku_MM_deleteMenuItemAndCreateSubMenu($parent, "verifyCommandPopupMenus", $rpArray, $cmd, off);
    { // add
        setParent -m $parent;
        menuItem
            -l (`uiRes("m_scriptEditorPanel.kClearHistory")` + " && " + `uiRes("m_scriptEditorPanel.kExecuteAll")`)
            -c "handleScriptEditorAction \"clearHistory\";handleScriptEditorAction \"executeAll\""
            -ecr false
            -rp "N"
            ;
        menuItem
            -l `uiRes("m_scriptEditorPanel.kQuickHelp")`
            -c ("handleScriptEditorAction \"showSelectedCmdQuickHelp\";\n"
                + "tabLayout -edit -selectTab $gCommandExecuterSideBarHelpForm $gCommandExecuterSideBar")
            -rp "S"
            -ecr false
            ;
        menuItem
            -l `uiRes("m_scriptEditorPanel.kClearHistory")`
            -c "handleScriptEditorAction \"clearHistory\""
            -rp "E"
            -ecr false
            ;
        menuItem
            -l `uiRes("m_scriptEditorPanel.kExecuteAll")`
            -c "handleScriptEditorAction \"executeAll\""
            -ecr false
            -rp "NE"
            ;
        { // Toggle visibility Tool layout
            string $cmd = "{"
                        +       "string $lowLayout = `iconTextCheckBox -q -p \"echoAllCommandsButton\"`;"
                        +       "int $vis = !`flowLayout -q -vis $lowLayout`;"
                        +       "flowLayout -e -vis $vis $lowLayout;"
                        + "}";
            menuItem
                -l "Toggle visibility Tool layout"
                -c $cmd
                -rp "SE"
                -ecr false
                ;
        }
    }
}
global proc Kohaku_MM_createPrefsCreationWindowPopupMenuItem(string $parent, string $textField){
    popupMenu -edit -deleteAllItems $parent;
    setParent -menu $parent;
    if(!`shelfLayout -exists "Kohaku_ExitMarkingMenuCommand"`) return;
    string $prefsLabelArray[];
    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
    for($shelfButton in $shelfButtonArray){
        string $label = `shelfButton -query -label $shelfButton`;
        if(gmatch($label, "Kohaku Marking Menu Prefs_*")) {
            $label = substitute("^Kohaku Marking Menu Prefs_", $label, "");
            appendStringArray($prefsLabelArray, {$label}, 1);
        }
    }
    for($prefsLabel in $prefsLabelArray){
        string $menuItem = `menuItem -label $prefsLabel -enableCommandRepeat false`;
        string $cmd = "textField -edit -text \"" + $prefsLabel + "\" \"" + $textField + "\"";
        menuItem -edit -command $cmd $menuItem;
    }
}
global proc Kohaku_MM_createOrUpdatePrefs(string $prefs){
    if($prefs == "") return;
    string $targetShelfButton;
    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
    for($shelfButton in $shelfButtonArray){
        if(`shelfButton -query -label $shelfButton` == ("Kohaku Marking Menu Prefs_" + $prefs)){
            $targetShelfButton = $shelfButton; 
            break;
        }
    }
    setParent `shelfLayout -query -fullPathName "Kohaku_ExitMarkingMenuCommand"`;
    global string $gKohaku_MM_shelfMenuMainShelf;
    global string $gKohaku_MM_shelfMenuSubShelfArray[];
    string $label = "Kohaku Marking Menu Prefs_" + $prefs;
    string $subShelfArrayString = stringArrayToString($gKohaku_MM_shelfMenuSubShelfArray, "\", \"");
    string $cmd = "$gKohaku_MM_shelfMenuMainShelf = \"" + $gKohaku_MM_shelfMenuMainShelf + "\";\n";
    if($subShelfArrayString != ""){
        $subShelfArrayString = "{\"" + $subShelfArrayString + "\"}";
        $cmd += "$gKohaku_MM_shelfMenuSubShelfArray = " + $subShelfArrayString + ";\n";
    }else{
        $cmd += "clear $gKohaku_MM_shelfMenuSubShelfArray;\n";
    }
    $cmd += "Kohaku_MM_selectPrefsComponent(\"" + $prefs + "\");";
    if($targetShelfButton != ""){
        shelfButton -edit -command $cmd $targetShelfButton;
    }else{
        $targetShelfButton = `shelfButton -label $label -command $cmd -image "commandButton.png" -imageOverlayLabel "Prefs"`;
    }
    { // shelfButtonのpopupMenuに名前のprefesがある場合は削除
        for($shelfButton in $shelfButtonArray){
            string $targetPopUpMenu;
            string $popUpMenuToShelfButtonArray[] = `shelfButton -q -popupMenuArray $shelfButton`;
            for($popUpMenuToShelfButton in $popUpMenuToShelfButtonArray){
                if(`popupMenu -query -button $popUpMenuToShelfButton` == 3
                    && !`popupMenu -query -altModifier $popUpMenuToShelfButton`
                    && !`popupMenu -query -ctrlModifier $popUpMenuToShelfButton`
                    && !`popupMenu -query -shiftModifier $popUpMenuToShelfButton`){
                        $targetPopUpMenu = $popUpMenuToShelfButton;
                }
            }
            string $menuItemArray[] = `popupMenu -query -itemArray $targetPopUpMenu`;
            string $targetMenuItemArray[];
            for($menuItem in $menuItemArray){
                string $label = `menuItem -query -label $menuItem`;
                if(`gmatch $label ("Prefs_" + $prefs + " :*")`){
                    appendStringArray($targetMenuItemArray, {$menuItem}, 1);
                }
            }
            for($targetMenuItem in $targetMenuItemArray) deleteUI -menuItem $targetMenuItem;
        }
    }
    { // ShelfButtonにeixitMarkingMenuCmdAbbreviationがついている場合はpopupMenuに登録
        for($shelfButton in $shelfButtonArray){
            string $imageOverlayLabel = `shelfButton -query -imageOverlayLabel $shelfButton`;
            if($imageOverlayLabel == "") continue;
            global string $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray[];
            if(stringArrayContains($imageOverlayLabel, $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray)){
                string $targetPopUpMenu;
                string $popUpMenuToShelfButtonArray[] = `shelfButton -q -popupMenuArray $shelfButton`;
                for($popUpMenuToShelfButton in $popUpMenuToShelfButtonArray){
                    if(`popupMenu -query -button $popUpMenuToShelfButton` == 3
                        && !`popupMenu -query -altModifier $popUpMenuToShelfButton`
                        && !`popupMenu -query -ctrlModifier $popUpMenuToShelfButton`
                        && !`popupMenu -query -shiftModifier $popUpMenuToShelfButton`){
                            $targetPopUpMenu = $popUpMenuToShelfButton;
                    }
                }
                setParent -m $targetPopUpMenu;
                menuItem
                    -label ("Prefs_" + $prefs + " : " + $imageOverlayLabel)
                    -command "// Prefs"
                    -enable false
                    -insertAfter ""
                    ;
            }
        }
    }
    global string $gKohaku_MM_selectedPrefs;
    $gKohaku_MM_selectedPrefs = $prefs;
    Kohaku_MM_local_recordDefaultPrefsToShelfButton();
    evalDeferred "source \"kohaku_markingMenu\"";
}
global proc Kohaku_MM_prefsCreationWindow(){
    if(!`shelfLayout -exists "Kohaku_ExitMarkingMenuCommand"`) return;
    string $window = `window`;
    window -edit
        -maximizeButton false
        -minimizeButton false
        -sizeable false
        -title "Create Or Update Prefs"
        $window
        ;
    columnLayout
        -columnAttach "both" 0
        -columnWidth 230
        -margins 5
        -rowSpacing 5
        ;
    string $textField = `textField`;
    string $cmd = "{"
                +     "$prefs = `textField -query -text " + $textField + "`;"
                +     "Kohaku_MM_createOrUpdatePrefs($prefs);evalDeferred \"deleteUI -window \\\"" + $window + "\\\"\";"
                + "}"
                ;
    $cmd = "eval \"" + `encodeString $cmd` + "\"";
    textField
        -edit
        -alwaysInvokeEnterCommandOnReturn true
        -enterCommand $cmd
        -placeholderText "Select existing Prefs from right click menu"
        $textField
        ;
    { // popupMenu
        string $popupMenu = `popupMenu -parent $textField`;
        string $popupMenuCmd = "Kohaku_MM_createPrefsCreationWindowPopupMenuItem("
            + "\"" + $popupMenu + "\", \"" + $textField + "\")";
        popupMenu -edit -postMenuCommand $popupMenuCmd $popupMenu;
    }
    button
        -label "Create Or Update"
        -command $cmd
        ;
    { // iti
        int $posArray[] = python("kohaku_MM_getCursorPosition()");
        int $sizeArray[] = python("kohaku_MM_getWindowSize(\"" + $window + "\")");
        int $xPos = $posArray[0] - int($sizeArray[0] / 2);
        int $yPos = $posArray[1] - int($sizeArray[1] / 2) - 42;
        window -edit -leftEdge $xPos -topEdge $yPos $window;
    }
    showWindow $window;
}
global proc Kohaku_MM_selectPrefs(string $prefs){
    if(!`shelfLayout -exists "Kohaku_ExitMarkingMenuCommand"`) return;
    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
    for($shelfButton in $shelfButtonArray){
        { // Main & Sub shelf設定
            string $label = `shelfButton -query -label $shelfButton`;
            if($label == ("Kohaku Marking Menu Prefs_" + $prefs)){
                eval `shelfButton -query -command $shelfButton`;
                continue;
            }
        }
    }
}
global proc Kohaku_MM_selectPrefsComponent(string $prefs){
    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
    global string $gKohaku_MM_selectedPrefs;
    for($shelfButton in $shelfButtonArray){
        string $shelfButtonLabel = `shelfButton -query -label $shelfButton`;
        if(`gmatch $shelfButtonLabel "Kohaku Marking Menu Prefs*"`) continue;
        string $targetPopUpMenu;
        string $popUpMenuToShelfButtonArray[] = `shelfButton -query -popupMenuArray $shelfButton`;
        for($popUpMenuToShelfButton in $popUpMenuToShelfButtonArray){
            if(`popupMenu -query -button $popUpMenuToShelfButton` == 3
                && !`popupMenu -query -altModifier $popUpMenuToShelfButton`
                && !`popupMenu -query -ctrlModifier $popUpMenuToShelfButton`
                && !`popupMenu -query -shiftModifier $popUpMenuToShelfButton`){
                    $targetPopUpMenu = $popUpMenuToShelfButton;
            }
        }
        string $menuItemArray[] = `popupMenu -query -itemArray $targetPopUpMenu`;
        string $imageOverlayLabel, $label;
        for($menuItem in $menuItemArray){
            $label = `menuItem -query -label $menuItem`;
            if(`gmatch $label ("Prefs_" + $prefs + " : *")`){
                $imageOverlayLabel = substitute(("Prefs_" + $prefs + " : "), $label, "");
            }
        }
        shelfButton -edit -imageOverlayLabel $imageOverlayLabel $shelfButton;
    }
    kohaku_MM_local_markingPrefs($prefs); // Marking Prefs
    $gKohaku_MM_selectedPrefs = $prefs;
    Kohaku_MM_local_recordDefaultPrefsToShelfButton; // Default Prefs
    evalDeferred "source \"kohaku_markingMenu\"";
}
global proc Kohaku_MM_recentCmdMenu(string $parent){
    
    setParent -m $parent;
    string $recentCmdArray[] = `repeatLast -q -cnl`;
    string $recentCmdStringArray[] = `repeatLast -q -cl`;
    int $index = 0;
    for($cmd in $recentCmdArray){
        $index++;
        if($cmd == "") continue;
		if($cmd == "Parent") $cmd = $recentCmdStringArray[$index]; // parent constraint and parent menu items have the same name,
        string $label = makeStringSingleLine($cmd);
        if(`size $label` > 25) $label = startString($label, 25) + "...";
        string $runTimeCmd = `kohaku_MM_local_getRunTimeCmd $cmd`;
        string $image;
        if($runTimeCmd != "") $image = `runTimeCommand -q -i $runTimeCmd`;
        string $menuItem = `menuItem
            -l $label
            -c $recentCmdStringArray[$index - 1]
            -i $image
            `
            ;
        string $radialPositionArray[] = {"N", "NW", "W", "SW", "S", "SE", "E", "NE"};
        if($index <= 8) menuItem -e -rp $radialPositionArray[$index - 1] $menuItem;
    }
}
global proc string Kohaku_MM_recordMainOrSubShelfToPrefsShelfButton(string $targetShelf, string $mainOrSub, int $checkBoxFlg){
    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
    string $prefsShelfButton;
    for($shelfButton in $shelfButtonArray){
        if(`shelfButton -query -label $shelfButton` == "Kohaku Marking Menu Prefs"){
            $prefsShelfButton = $shelfButton;
            break;
        }
    }
    global string $gKohaku_MM_shelfMenuMainShelf;
    global string $gKohaku_MM_shelfMenuSubShelfArray[];
    { // 値を入れる
        if($mainOrSub == "Main"){
            $gKohaku_MM_shelfMenuMainShelf = $targetShelf;
        }else{
            if($checkBoxFlg){
                if(!stringArrayContains($targetShelf, $gKohaku_MM_shelfMenuSubShelfArray)){
                    appendStringArray($gKohaku_MM_shelfMenuSubShelfArray, {$targetShelf}, 1);
                    { // 並び方を揃える
                        global string $gShelfTopLevel;
                        string $shelfArray[] = `shelfTabLayout -query -childArray $gShelfTopLevel`;
                        string $subShelfArray[] = $gKohaku_MM_shelfMenuSubShelfArray;
                        clear $gKohaku_MM_shelfMenuSubShelfArray;
                        for($shelf in $shelfArray){
                            if(stringArrayContains($shelf, $subShelfArray)){
                                appendStringArray($gKohaku_MM_shelfMenuSubShelfArray, {$shelf}, 1);
                            }
                        }
                    }
                }
            }else{
                if(stringArrayContains($targetShelf, $gKohaku_MM_shelfMenuSubShelfArray)){
                    $gKohaku_MM_shelfMenuSubShelfArray = stringArrayRemove({$targetShelf}, $gKohaku_MM_shelfMenuSubShelfArray);
                }
            }
        }
    }
    { // 選択されているPrefsの更新
        global string $gKohaku_MM_selectedPrefs;
        if($gKohaku_MM_selectedPrefs != ""){
            string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
            for($shelfButton in $shelfButtonArray){
                if(`shelfButton -query -label $shelfButton` == "Kohaku Marking Menu Prefs_" + $gKohaku_MM_selectedPrefs){
                    string $cmd = `shelfButton -query -command $shelfButton`;
                    string $cmdArray[] = stringToStringArray($cmd, "\n");
                    $cmdArray[0] = "$gKohaku_MM_shelfMenuMainShelf = \"" + $gKohaku_MM_shelfMenuMainShelf + "\";";
                    string $subShelfArrayString = stringArrayToString($gKohaku_MM_shelfMenuSubShelfArray, "\", \"");
                    if($subShelfArrayString != ""){
                        $cmdArray[1] = "$gKohaku_MM_shelfMenuSubShelfArray = {\"" + $subShelfArrayString + "\"};";
                    }else{
                        $cmdArray[1] = "clear $gKohaku_MM_shelfMenuSubShelfArray;";
                    }
                    $cmd = stringArrayToString($cmdArray, "\n");
                    shelfButton -edit -command $cmd $shelfButton;
                    break;
                }
            }
        }
    }
    return Kohaku_MM_local_recordDefaultPrefsToShelfButton();
}
global proc Kohaku_MM_buildShelfMenuItemString(){
    global string $gShelfTopLevel; // shelf.mel
    string $selectedShelf = `shelfTabLayout -query -selectTab $gShelfTopLevel`; // シェルフの選択を記憶
    global string $gKohaku_MM_shelfMenuItemString;
    $gKohaku_MM_shelfMenuItemString = "";
    int $mainMenuItemNum = 0;
    { // Sub shelf
        global string $gKohaku_MM_shelfMenuSubShelfArray[];
        global string $gKohaku_MM_shelfSubMenuItemStringArray[];
        clear $gKohaku_MM_shelfSubMenuItemStringArray;
        string $subShelfNameArray[];
        for($subShelf in $gKohaku_MM_shelfMenuSubShelfArray){
            if(`shelfLayout -exists $subShelf`){
                $mainMenuItemNum++;
                appendStringArray($gKohaku_MM_shelfSubMenuItemStringArray, {""}, 1);
                appendStringArray($subShelfNameArray, {$subShelf}, 1);
                shelfTabLayout -edit -selectTab $subShelf $gShelfTopLevel; // 選択でmelが読まれる
                string $shelfButtonArray[] = `shelfLayout -query -childArray $subShelf`;
                int $index = size($gKohaku_MM_shelfSubMenuItemStringArray) - 1;
                for($shelfButton in $shelfButtonArray){
                    $gKohaku_MM_shelfSubMenuItemStringArray[$index] = // += だとエラー
                        $gKohaku_MM_shelfSubMenuItemStringArray[$index] + `kohaku_MM_local_buildMenuItemString $shelfButton $mainMenuItemNum`;
                }
            }
        }
        int $index;
        for($subMenuItemString in $gKohaku_MM_shelfSubMenuItemStringArray){
            $gKohaku_MM_shelfMenuItemString += "menuItem\n"
                                        + "    -label \"" + $subShelfNameArray[$index] + "\"\n"
                                        + "    -subMenu true\n"
                                        + "    ;\n"
                                        ;
            $gKohaku_MM_shelfMenuItemString += "setParent -m ..;\n";
            $index++;
        }
    }
    { // Main shelf
        global string $gKohaku_MM_shelfMenuMainShelf;
        if($gKohaku_MM_shelfMenuMainShelf != ""){
            if(`shelfLayout -exists $gKohaku_MM_shelfMenuMainShelf`){
                shelfTabLayout -edit -selectTab $gKohaku_MM_shelfMenuMainShelf $gShelfTopLevel; // 選択でmelが読まれる
                string $shelfButtonArray[] = `shelfLayout -query -childArray $gKohaku_MM_shelfMenuMainShelf`;
                for($shelfButton in $shelfButtonArray){
                    $mainMenuItemNum++;
                    $gKohaku_MM_shelfMenuItemString += `kohaku_MM_local_buildMenuItemString $shelfButton $mainMenuItemNum`;
                }
            }
        }
    }
    shelfTabLayout -e -st $selectedShelf $gShelfTopLevel; // 選択を戻す
}
global proc Kohaku_MM_etcMenu(string $parent){
    setParent -m $parent;
    popupMenu -e -dai $parent;
    { // Kohaku DagMenu
        menuItem -l "Modify Kohaku Marking Menu" -sm on; // Modify:変更
        { // 主シェルフ選択
            menuItem -l "Main shelf selection" -sm on;
            { // Sub menu
                radioMenuItemCollection;
                global string $gShelfTopLevel;
                string $shelfArray[] = `shelfTabLayout -q -ca $gShelfTopLevel`;
                global string $gKohaku_MM_shelfMenuMainShelf;
                global string $gKohaku_MM_selectedPrefs;
                for($shelf in $shelfArray){
                    if($shelf == "Kohaku_ExitMarkingMenuCommand") continue;
                    int $rbFlg = off;
                    if($gKohaku_MM_shelfMenuMainShelf == $shelf){
                        $rbFlg = on;
                    }
                    string $cmd = "Kohaku_MM_recordMainOrSubShelfToPrefsShelfButton \"" + $shelf + "\" \"Main\" \"0\";"
                                + "Kohaku_MM_buildShelfMenuItemString;\n"
                                ;
                    menuItem
                        -label $shelf
                        -rb $rbFlg
                        -c $cmd
                        -ecr false
                        ;
                }
                string $cmd = "Kohaku_MM_recordMainOrSubShelfToPrefsShelfButton \"\" \"Main\" \"0\";"
                            + "Kohaku_MM_buildShelfMenuItemString"
                            ;
                global string $gKohaku_MM_shelfMenuMainShelf;
                menuItem
                    -l "None"
                    -rb ($gKohaku_MM_shelfMenuMainShelf == "")
                    -c $cmd
                    -ecr false
                    ;
            }
            setParent -m ..;
        }
        { // サブシェルフ選択
            string $menuName = "Kohaku_MM_subShelfSelection";
            string $parent = "kohaku_MM_backstageWindow";
            { // tearOff用のpopupMenuを仮に作っておく
                string $parentMenu = `setParent -query -menu`; // menuの親を取得しておく
                if(`menu -exists $menuName`) deleteUI -menu $menuName;
                menu -label "Sub Shelf Selection" -parent $parent $menuName;
                global string $gShelfTopLevel;
                string $shelfArray[] = `shelfTabLayout -q -ca $gShelfTopLevel`;
                global string $gKohaku_MM_selectedPrefs;
                for($shelf in $shelfArray){
                    if($shelf == "Kohaku_ExitMarkingMenuCommand") continue;
                    //-checkBox false
                    global string $gKohaku_MM_shelfMenuSubShelfArray[];
                    int $checkBoxFlg = off;
                    if(stringArrayContains($shelf, $gKohaku_MM_shelfMenuSubShelfArray)) $checkBoxFlg = on;
                    string $cmd = "Kohaku_MM_recordMainOrSubShelfToPrefsShelfButton \"" + $shelf + "\" \"Sub\" #1;\n" // #1:checkBox
                                + "Kohaku_MM_buildShelfMenuItemString;\n"
                                ;
                    menuItem
                        -label $shelf
                        -checkBox $checkBoxFlg
                        -c $cmd
                        -ecr false
                        ;
                }
                setParent -menu $parentMenu; // menuの親を戻す
            }
            string $cmd = "Kohaku_MM_showTearOffMenu(\"" + $menuName + "\", \"" + "m_menubar_" + $parent + "\")";
            menuItem -l "Sub Shelf Selection" -command $cmd;
        }
        { // Prefs selection
            menuItem -label "Select Prefs" -subMenu true -enableCommandRepeat false;
            { // Sub menu
                if(`shelfLayout -exists "Kohaku_ExitMarkingMenuCommand"`){
                    string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
                    for($shelfButton in $shelfButtonArray){
                        string $label = `shelfButton -query -label $shelfButton`;
                        if(`gmatch $label "Kohaku Marking Menu Prefs_*"`){
                            $label = `substitute "^Kohaku Marking Menu Prefs_" $label ""`;
                            menuItem
                                -label $label
                                -c ("Kohaku_MM_selectPrefs " + $label)
                                -ecr false
                                ;
                        }
                        $rbFlg = off;
                    }
                }
            }
            setParent -m ..;
        }
        { // Prefs creation
            menuItem
                -label "Create Or Update Prefs"
                -command Kohaku_MM_prefsCreationWindow
                -enableCommandRepeat false
                ;
        }
        setParent -m ..;
    }
}
global proc Kohaku_MM_editObjectSelectionMask(string $parent){
    // なーぶすとうをオブジェクトモードにしたときにCVの選択が残るのを無くす
    string $itemArray[] = `popupMenu -query -itemArray $parent`;
    for($menuItem in $itemArray){
        if(`menuItem -q -l $menuItem` == (uiRes("m_dagMenuProc.kObjectMode"))){
            string $cmd = "eval -ue false \"Kohaku_MM_clearCVHullEp\"";
            $cmd = "evalDeferred -lp \"" + `encodeString $cmd` + "\"";
            string $originCmd = `menuItem -q -c $menuItem`;
            menuItem -e -c ($originCmd + ";" + $cmd) $menuItem;
        }
    }
}
global proc Kohaku_MM_etcCommandPop(string $parent){
    popupMenu -e -dai $parent;
    setParent -m $parent;
    { // Current Sacred Tool
        global string $gCurrentSacredTool; // toolbox.mel
        string $runTimeCmd = `kohaku_MM_local_getRunTimeCmd $gCurrentSacredTool`;
        string $label = `kohaku_MM_local_getLabel $runTimeCmd`;
        string $image = `kohaku_MM_local_getCtxIcon $gCurrentSacredTool`;
        menuItem
            -l $label
            -c $runTimeCmd
            -ecr false // Match Tool Box
            -i $image
            -rp "N"
            ;
    }
    { // Non Sacred Tool;
        global string $gKohaku_MM_collectNonSacredToolArray[];
        if(size($gKohaku_MM_collectNonSacredToolArray)){
            string $ctx = $gKohaku_MM_collectNonSacredToolArray[0];
            string $label, $runTimeCmd; 
            { // polySlideEdgeContext has no title
                $runTimeCmd = `kohaku_MM_local_getRunTimeCmd $ctx`;
                if($runTimeCmd != ""){
                    $label = `kohaku_MM_local_getLabel $runTimeCmd`;
                }else{
                    if(`contextInfo -ex $ctx`) $label = `contextInfo -t $ctx`;
                }
            }
            if($label != ""){ // safety measure 安全対策
                menuItem
                    -l $label
                    -c ("setToolTo " + $ctx)
                    -ecr false // Match Tool Box
                    -i `contextInfo -i1 $ctx`
                    -rp "E"
                    ;
            }
        }
    }
    { // repeat RunTime Command
        string $recentCmdArray[] = `repeatLast -q -cnl`;
        string $recentCmdStringArray[] = `repeatLast -q -cl`;
        int $index = 0;
        string $runTimeCmd, $label;
        for ($cmd in $recentCmdArray){
            $index++;
            if($cmd == "") continue;
            if($cmd == "Parent") $cmd = $recentCmdStringArray[$index - 1]; // parent constraint and parent menu items have the same name
            { // Excluding Tool 除く
                if(size(`match "setToolTo" $cmd`)) continue;
                $runTimeCmd = `kohaku_MM_local_getRunTimeCmd $cmd`;
                if(`runTimeCommand -ex $runTimeCmd`){
                    if(!`endsWith $runTimeCmd "Tool"` || $runTimeCmd == "CompleteCurrentTool"){
                        $label = $cmd; // In runTimeCmd, Delete History, etc. is displayed as History.
                        break;
                    }
                }
            }
        }
        if($label != ""){
            menuItem
                -l $label
                -c $recentCmdStringArray[$index - 1]
                -ecr true
                -i `runTimeCommand -q -i $runTimeCmd`
                -rp "W"
                ;
        }
    }
    { // Undo & Redo
        string $cmdArray[] = {"Undo", "Redo"};
        string $rpArray[] = {"SW", "SE"};
        string $labelArray[] = {`uiRes "m_buildEditMenu.kEditUndo"`,
            `uiRes "m_buildEditMenu.kEditRedo"`};
        for($i = 0; $i < 2; $i++){
            string $info = `eval("undoInfo -q -" + tolower($cmdArray[$i]) + "Name")`;
            string $label = $labelArray[$i];
            if($info != ""){
                string $tokens[];
                tokenize $info $tokens;
                if(`size $tokens` > 1) $info = $tokens[0];
                if(`size $info` > 25)
                    $info = startString($info, 25) + "...";
                $label += " \"" + $info + "\"";
            }
            if(isTrue ($cmdArray[$i] + "Available")){   
                menuItem
                    -l $label
                    -c $cmdArray[$i]
                    -ecr false
                    -i (`tolower $cmdArray[$i]` + "_s.png")
                    -rp $rpArray[$i]
                    ;
            }
        }
    }
    { // RepeatLast
        string $label;
        if(`repeatLast -q -numberOfHistoryItems` != 0){
            string $recentCmdNameArray[] = `repeatLast -cnl 1`;
            $label = $recentCmdNameArray[0];
        }
        if($label == "Parent"){ // parent constraint and parent menu items have the same name
            string $recentCmdStringArray[] = `repeatLast -cl 1`;
            $label = $recentCmdStringArray[0];
        }
        $label = makeStringSingleLine($label);
        if(`size $label` > 25)
            $label = startString($label, 25) + "...";
        if(`repeatLast -q -numberOfHistoryItems` != 0){
            menuItem 
                -l (`uiRes "m_buildEditMenu.kEditRepeat"` + " \"" + $label + "\"")
                -c "RepeatLast"
                -ecr false
                -rp "S"
                ;
        }
    }
    { // Recent Commands
        string $menuItem = "Kohaku_MM_recentCmdMenu";
        menuItem
            -l `uiRes("m_HotboxMenus.kRecentCommands")`
            -rp "NE"
            -pmc ("Kohaku_MM_recentCmdMenu \"" + $parent + "|" + $menuItem + "\"")
            -pmo true
            -sm on
            $menuItem
            ;
        setParent -m ..;
    }
    { // Etc
        string $panel = kohaku_MM_local_getAncestor($parent, 2);
        string $menuItemName = $panel + "Kohaku_MM_etcMenu";
        menuItem
            -l "Etc"
            -rp "NW"
            -sm on
            -pmc ("Kohaku_MM_etcMenu \"" + $parent + "|" + $menuItemName + "\"")
            -pmo true
            $menuItemName
            ;
        setParent -m ..;
    }
    { // Put in a script job to kill the right click
        global int $gKohaku_MM_rightClickScriptJobNum;
        string $menuItemArray[] = `popupMenu -q -ia $parent`;
        for($menuItem in $menuItemArray){
            $menuItem = $parent + "|" + $menuItem;
            string $rp = `menuItem -q -rp $menuItem`;
            switch($rp){
                case "N":
                case "NW":
                case "W":
                case "SW":
                case "S":
                case "SE":
                case "E":
                case "NE":
                    kohaku_MM_local_killRightClickScriptJob $menuItem;
                    break;
            }
        }
    }
}
global proc Kohaku_MM_shelfPop(string $parent){
    popupMenu -e -dai $parent;
    setParent -m $parent;
    { // Shelf menu & Sub menu
        global string $gKohaku_MM_shelfMenuItemString;
        eval($gKohaku_MM_shelfMenuItemString); // Creating MenuItem
        string $menuItemArray[] = `popupMenu -q -ia $parent`;
        int $index, $sumMenuIndex;
        for($menuItem in $menuItemArray){
            $menuItem = $parent + "|" + $menuItem;
            { // rp
                string $radialPositionArray[] = {"N", "NW", "W", "SW", "S", "SE", "E", "NE"};
                string $rp = `menuItem -q -rp $menuItem`;
                if($rp == "" && !`menuItem -q -isOptionBox $menuItem` && !`menuItem -q -d $menuItem`){
                    if(size($radialPositionArray) >= ($index + 1)){
                        menuItem -e -rp $radialPositionArray[$index] $menuItem;
                        $index++;
                    }
                }
            }
            { // edit PMC
                global string $gKohaku_MM_shelfSubMenuItemStringArray[];
                int $size = size($gKohaku_MM_shelfSubMenuItemStringArray);
                if(`menuItem -query -subMenu $menuItem` && $size > $sumMenuIndex){
                    string $menuItemName = "subMenu";
                    string $cmd = "if(`popupMenu -query -numberOfItems \"" + $menuItem + "\"` != 0)"
                                + " popupMenu -e -dai \"" + $menuItem + "\";\n" // dai必要
                                + "setParent -m \"" + $menuItem + "\";\n" // setParent必要
                                + "eval($gKohaku_MM_shelfSubMenuItemStringArray[" + $sumMenuIndex + "]);\n"
                                + "Kohaku_MM_radialPoint \"" + $menuItem + "\";"
                                + "Kohaku_MM_deleteMenuItemAndCreateSubMenu \"" + $menuItem + "\""
                                + " \"" + $menuItemName + "\""
                                + " {\"\"}"
                                + " \"setParent -m \\\"" + $menuItem + "|Kohaku_MM_" + $menuItemName + "\\\";"
                                + "eval($gKohaku_MM_shelfSubMenuItemStringArray[" + $sumMenuIndex + "]);"
                                + "Kohaku_MM_radialPoint \\\"" + $menuItem + "|Kohaku_MM_" + $menuItemName + "\\\";\""
                                + " off\n;"
                                ;
                    menuItem -edit -postMenuCommand $cmd -postMenuCommandOnce true $menuItem;
                    $sumMenuIndex++;
                }
            }
        }
    }
    { // Put in a script job to kill the right click
        string $menuItemArray[] = `popupMenu -q -ia $parent`;
        for($menuItem in $menuItemArray){
            $menuItem = $parent + "|" + $menuItem;
            string $rp = `menuItem -q -rp $menuItem`;
            switch($rp){
                case "N":
                case "NW":
                case "W":
                case "SW":
                case "S":
                case "SE":
                case "E":
                case "NE":
                    kohaku_MM_local_killRightClickScriptJob $menuItem;
                    break;
            }
        }
    }
}
global proc Kohaku_MM_changeMenuToSubMenu(string $parent ,string $targetProc){
    setParent -m $parent;
    { // Put in a script job to kill the right click
        global int $gKohaku_MM_rightClickScriptJobNum;
        string $menuItemArray[] = `popupMenu -q -ia $parent`;
        int $rpFlg = false;
        for($menuItem in $menuItemArray){
            $menuItem = $parent + "|" + $menuItem;
            if(string(`menuItem -q -rp $menuItem`) != ""){
                kohaku_MM_local_killRightClickScriptJob $menuItem;
                $rpFlg = true;
            }
        }
        { // ViewCubeMenuの場合 rpがないので判定
            if(!$rpFlg){
                global int $gKohaku_MM_rightClickScriptJobNum;
                scriptJob -kill $gKohaku_MM_rightClickScriptJobNum;
            }
        }
    }
    Kohaku_MM_deleteMenuItemAndCreateSubMenu $parent $targetProc {""} $targetProc on;
}
proc kohaku_MM_local_initializeExitMarkingMenuCommand(){
    if(!`shelfLayout -exists "Kohaku_ExitMarkingMenuCommand"`) return;
    global string $gShelfTopLevel;
    string $selectedShelf = `shelfTabLayout -q -st $gShelfTopLevel`; // シェルフの選択を取得
    shelfTabLayout -e -st "Kohaku_ExitMarkingMenuCommand" $gShelfTopLevel;
    int $targetShelfIndex = `shelfTabLayout -q -sti $gShelfTopLevel`;
    shelfTabLayout -e -st $selectedShelf $gShelfTopLevel; // シェルフの選択を戻す
    string $shelfButtonArray[] = `shelfLayout -q -ca "Kohaku_ExitMarkingMenuCommand"`;
    int $index;
    for($shelfButton in $shelfButtonArray){
        if(`separator -ex $shelfButton`) continue; // Separator
        { // Tool button
            int $toolButtonFlg = `kohaku_MM_local_countermeasureToolButton $shelfButton "Kohaku_ExitMarkingMenuCommand" $targetShelfIndex`;
            if($toolButtonFlg) continue;
        }
        string $imageOverlayLabel = `shelfButton -q -iol $shelfButton`;
        if($imageOverlayLabel != ""){
            { // PrefsとeixitMarkingMenuCmdAbbreviation以外のimageOverlayLabelを削除
                if($imageOverlayLabel != "Prefs"){
                    global string $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray[];
                    if(stringArrayFind($imageOverlayLabel, 0, $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray) == -1){
                        shelfButton -edit -imageOverlayLabel "" $shelfButton;
                        continue;
                    }
                }
            }
            kohaku_MM_local_registerExitMarkingMenuCommandComponent($shelfButton, $imageOverlayLabel);
        }
    }
}
{ // Build exit marking menu command label window
    string $cmd = "def kohaku_MM_buildExitMarkingMenuCmdLabelWindow(objectName):\n"
                      + "    try:\n"
                      + "        from PySide6.QtCore import Qt\n"
                      + "        from PySide6.QtWidgets import QHBoxLayout, QLabel, QWidget\n"
                      + "    except:\n"
                      + "        from PySide2.QtCore import Qt\n"
                      + "        from PySide2.QtWidgets import QHBoxLayout, QLabel, QWidget\n"
                      + "    imageLabel = QLabel()\n"
                      + "    imageLabel.setObjectName(\"ImageLabel\")\n"
                      + "    imageLabel.setStyleSheet(\"border: 0px;\")\n"
                      + "    textLabel = QLabel()\n"
                      + "    textLabel.setObjectName(\"TextLabel\")\n"
                      + "    textLabel.setStyleSheet(\"color: white; border: 0px;\")\n"
                      + "    layout = QHBoxLayout()\n"
                      + "    layout.addWidget(imageLabel)\n"
                      + "    layout.addWidget(textLabel)\n"
                      + "    layout.setContentsMargins(3, 1, 23, 1)\n"
                      + "    qWidget = QWidget(gKohaku_MM_mayaMainWindow)\n"
                      + "    qWidget.setObjectName(objectName)\n"
                      + "    qWidget.setLayout(layout)\n"
                      + "    qWidget.setStyleSheet(\"border: 1px solid black; background-color: rgb(82, 133, 166)\")\n"
                      + "    qWidget.setWindowFlags(Qt.Window | Qt.FramelessWindowHint | \n"
                      + "                           Qt.NoDropShadowWindowHint | Qt.WindowStaysOnTopHint)"
                      ;
    python($cmd);
}
{ // Edit exit marking menu command label window
    string $cmd = "def kohaku_MM_editExitMarkingMenuCmdLabelWindow(objectName, image, text):\n"
                      + "    try:\n"
                      + "        from PySide6.QtCore import Qt\n"
                      + "        from PySide6.QtGui import QPixmap\n"
                      + "        from PySide6.QtWidgets import QLabel, QWidget\n"
                      + "    except:\n"
                      + "        from PySide2.QtCore import Qt\n"
                      + "        from PySide2.QtGui import QPixmap\n"
                      + "        from PySide2.QtWidgets import QLabel, QWidget\n"
                      + "    targetWindow = gKohaku_MM_mayaMainWindow.findChild(QWidget, objectName, Qt.FindDirectChildrenOnly)\n"
                      + "    imageLabel = targetWindow.findChild(QLabel, \"ImageLabel\")\n"
                      + "    imageLabel.setPixmap(QPixmap(\":/\" + image).scaled(20, 20))\n"
                      + "    textLabel = targetWindow.findChild(QLabel, \"TextLabel\")\n"
                      + "    textLabel.setText(text)"
                      ;
    python($cmd);
}
{ // Get cursor position
    string $cmd = "try:\n"
                + "    from PySide6.QtGui import QCursor\n"
                + "except:\n"
                + "    from PySide2.QtGui import QCursor\n"
                + "def kohaku_MM_getCursorPosition():\n"
                + "    return [QCursor.pos().x(), QCursor.pos().y()]"
                ;
    python($cmd);
}
{ // Get mouse buttons
    string $cmd = "try:\n"
                      + "    from PySide6.QtGui import QGuiApplication\n"
                      + "except:\n"
                      + "    from PySide2.QtGui import QGuiApplication\n"
                      + "def kohaku_MM_getMouseButtons():\n"
                      + "    return QGuiApplication.mouseButtons()"
                      ;
    python($cmd);
}
{ // Get window size
    string $cmd = "try:\n"
                + "    from PySide6.QtWidgets import QWidget\n"
                + "    from shiboken6 import wrapInstance\n"
                + "except:\n"
                + "    from PySide2.QtWidgets import QWidget\n"
                + "    from shiboken2 import wrapInstance\n"
                + "from maya.OpenMayaUI import MQtUtil\n"
                + "def kohaku_MM_getWindowSize(objectName):\n"
                + "    ptr = MQtUtil.findWindow(objectName)\n"
                + "    widget = wrapInstance(int(ptr), QWidget)\n"
                + "    widget.adjustSize()\n"
                + "    return [widget.frameSize().width(), widget.frameSize().height()]"
                ;
    python($cmd);
}
{ // Install eventFilter to markingMenuWindow
    // MarkingMenuが表示されるとmarkingMenuWindowという名前のQWidgetが追加されるので
    // その親であるmodelPanelにeventフィルターを付けてmarkingMenuWindowが追加されたら
    // markingMenuWindowにeventフィルターを付ける
    string $cmd = "try:\n"
                + "    from PySide6.QtCore import QEvent, QEventLoop, QObject, Qt\n"
                + "    from PySide6.QtGui import QGuiApplication\n"
                + "    from PySide6.QtWidgets import QMenu, QWidget,         QWidgetAction\n"
                + "    from shiboken6 import wrapInstance\n"
                + "except:\n"
                + "    from PySide2.QtCore import QEvent, QEventLoop, QObject, Qt\n"
                + "    from PySide2.QtGui import QGuiApplication\n"
                + "    from PySide2.QtWidgets import QMenu, QWidget\n"
                + "    from shiboken2 import wrapInstance\n"
                + "from maya.OpenMayaUI import MQtUtil\n"
                + "from maya import mel\n"
                + "class Kohaku_MM_MainWindowFilter(QObject):\n"
                + "    def eventFilter(self, watched: QObject, event: QEvent):\n"
                + "        if event.type() == QEvent.KeyPress:\n"
                + "            if event.key() == Qt.Key_A:\n"
                + "                mel.eval(\"$gKohaku_MM_pressedInMarkingMenukey = \\\"A\\\"\")\n"
                + "                watched.findChild(QEventLoop).quit()\n"
                + "            if event.key() == Qt.Key_Z:\n"
                + "                mel.eval(\"$gKohaku_MM_pressedInMarkingMenukey = \\\"Z\\\"\")\n"
                + "                watched.findChild(QEventLoop).quit()\n"
                + "            if event.key() == Qt.Key_X:\n"
                + "                mel.eval(\"$gKohaku_MM_pressedInMarkingMenukey = \\\"X\\\"\")\n"
                + "                watched.findChild(QEventLoop).quit()\n"
                + "        return False\n"
                + "class Kohaku_MM_MarkingMenuWindowFilter(QObject):\n"
                + "    def eventFilter(self, watched: QObject, event: QEvent):\n"
                + "        if event.type() == QEvent.Wheel:\n"
                + "            if event.angleDelta().y() != 0:\n"
                + "                mel.eval(\"$gKohaku_MM_wheelAngleDelta = \" + str(event.angleDelta().y()))\n"
                + "            else :\n"
                + "                mel.eval(\"$gKohaku_MM_wheelAngleDelta = \" + str(event.angleDelta().x()))\n"
                + "            watched.findChild(QEventLoop).quit()\n"
                + "        elif event.type() == QEvent.Show:\n"
                + "            if gKohaku_MM_toggleNoModifierMakingMenuVisible:\n"
                + "                if QGuiApplication.keyboardModifiers() == Qt.NoModifier:\n"
                + "                    watched.hide()\n"
                + "        return False\n"
                + "class Kohaku_MM_ModelPanelFilter(QObject):\n"
                + "    def eventFilter(self, watched: QObject, event: QEvent, markingMenuFilter = Kohaku_MM_MarkingMenuWindowFilter(), mainWindowFilter = Kohaku_MM_MainWindowFilter()) :\n"
                + "        if event.type() == QEvent.ChildPolished :\n" // ChildPolished
                + "            ptr = MQtUtil.findControl(\"markingMenuWindow\")\n"
                + "            if ptr != None: \n"
                + "                widget = wrapInstance(int(ptr), QWidget)\n"
                + "                widget.installEventFilter(markingMenuFilter)\n"
                + "                global gKohaku_MM_mayaMainWindow\n"
                + "                gKohaku_MM_mayaMainWindow.installEventFilter(mainWindowFilter)\n"
                + "        elif event.type() == QEvent.ChildRemoved :\n"
                + "            ptr = MQtUtil.findControl(\"markingMenuWindow\")\n"
                + "            if ptr == None: \n"
                + "                watched.removeEventFilter(self)\n"
                + "                mainWindowPtr = MQtUtil.mainWindow()\n"
                + "                mainWindow = wrapInstance(int(mainWindowPtr), QWidget)\n"
                + "                mainWindow.removeEventFilter(mainWindowFilter)\n"
                + "        return False\n"
                + "def kohaku_MM_setMarkingMenuEventFilter(markingMenuName, filter = Kohaku_MM_ModelPanelFilter()):\n"
                + "    ptr = MQtUtil.findControl(markingMenuName)\n"
                + "    menu = wrapInstance(int(ptr), QMenu)\n"
                + "    panel = menu.parent()\n"
                + "    panel.installEventFilter(filter)\n"
                + "if \"gKohaku_MM_toggleNoModifierMakingMenuVisible\" not in globals():\n"
                + "    gKohaku_MM_toggleNoModifierMakingMenuVisible = False"
                ;
    python($cmd);
}
{ // Show Exit Marking Menu Command Label Window
    $cmd = "try:\n"
         + "    from PySide6.QtGui import QCursor\n"
         + "    from PySide6.QtCore import QTimer\n"
         + "except:\n"
         + "    from PySide2.QtGui import QCursor\n"
         + "    from PySide2.QtCore import QTimer\n"
         + "def kohaku_MM_showExitMarkingMenuCmdLabelWindow(objectName):\n"
         + "    window = gKohaku_MM_mayaMainWindow.findChild(QWidget, objectName, Qt.FindDirectChildrenOnly)\n"
         + "    window.move(\n"
         + "                (QCursor.pos().x() - (window.frameSize().width() / 2)), \n"
         + "                (QCursor.pos().y() - (window.frameSize().height() / 2))\n"
         + "               )\n"
         + "    window.show()\n"
         + "    def sendEvent() : window.hide()\n"
         + "    cmd = sendEvent\n"
         + "    QTimer.singleShot(250, cmd)"
         ;
    python($cmd);
}
{ // initialize
    string $windowName = "kohaku_MM_backstageWindow";
    { // BackstageWindow
        if(!`window -exists $windowName`) window -menuBar true $windowName;
    }
    scriptJob -p $windowName -e "ToolChanged" "Kohaku_MM_collectNonSacredTool";
    Kohaku_MM_local_createKohakuExitMarkingMenuCommandShelf();
    kohaku_MM_local_initializeExitMarkingMenuCommand();
    { // build Kohaku_MM_AbbreviationCommand Proc
        for($Abbreviation in $gKohaku_MM_eixitMarkingMenuCmdAbbreviationArray){
            string $proc = "Kohaku_MM_" + $Abbreviation + "_Command";
            if(!`exists $proc`){
                eval ("global proc " + $proc + "(string $label){}");
            }
        }
    }
    { // Main & Sub menuをglobal変数に入れる
        { // シェルフを選択するとmelが読み込まれる
            global string $gShelfTopLevel;
            string $originShelf = `shelfTabLayout -query -selectTab $gShelfTopLevel`;
            shelfTabLayout -edit -selectTab "Kohaku_ExitMarkingMenuCommand" $gShelfTopLevel;
            shelfTabLayout -edit -selectTab $originShelf $gShelfTopLevel;
        }
        string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
        for($shelfButton in $shelfButtonArray){
            if(`shelfButton -query -label $shelfButton` == "Kohaku Marking Menu Prefs"){
                eval `shelfButton -query -command $shelfButton`;
                break;
            }
        }
    }
    Kohaku_MM_buildShelfMenuItemString();
    { // Set shelf button popup menu
        string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
        for($shelfButton in $shelfButtonArray){
            string $label = `shelfButton -query -label $shelfButton`;
            if(`gmatch $label "Kohaku Marking Menu Prefs*"`) continue;
            string $targetPopupMenu;
            string $popupMenuArray[] = `shelfButton -query -popupMenuArray $shelfButton`;
            for($popupMenu in $popupMenuArray){
                if(`popupMenu -query -button $popupMenu` == 3
                    && !`popupMenu -query -altModifier $popupMenu`
                    && !`popupMenu -query -ctrlModifier $popupMenu`
                    && !`popupMenu -query -shiftModifier $popupMenu`){
                    $targetPopupMenu = $popupMenu;
                    break;
                }
            }
            { // Add menu item to register command
                string $registerRightClickAndRightReleaseMenuItem
                    = ("Kohaku_MM_registerCommand_" + $targetPopupMenu);
                if(!`menuItem -exists $registerRightClickAndRightReleaseMenuItem`){
                    string $itemArray[] = `popupMenu -query -itemArray $targetPopupMenu`;
                    setParent -menu $targetPopupMenu;
                    if(size($itemArray) == 0){
                        menuItem -subMenu true $registerRightClickAndRightReleaseMenuItem;
                    }else{
                        string $targetItem;
                        for($item in $itemArray){
                            string $itemLabel = `menuItem -query -label $item`;
                            if(`gmatch $itemLabel "Prefs_*"`) $targetItem = $item;
                        }
                        menuItem -insertAfter $targetItem -subMenu true $registerRightClickAndRightReleaseMenuItem;                       
                    }
                    menuItem
                        -edit
                        -label "Register Command"
                        -postMenuCommand ("Kohaku_MM_buildRegisterExitMarkingMenuCmdMenu("
                                        + "\"" + $registerRightClickAndRightReleaseMenuItem + "\""
                                        + ", \"" + $shelfButton + "\")")
                        $registerRightClickAndRightReleaseMenuItem
                        ;
                    setParent -menu ..;
                }
            }
            { // Prefs menuItem enable false
                string $menuItemArray[] = `popupMenu -query -itemArray $targetPopupMenu`;
                for($menuItem in $menuItemArray){
                    string $label = `menuItem -query -label $menuItem`;
                    if(`gmatch $label "Prefs_*"`){
                        int $enable = `menuItem -query -enable $menuItem`;
                        if($enable == true){
                            menuItem -edit -enable false $menuItem;
                        }
                    }
                }
            }
        }
    }
    { // Fixes global proc (Fixes:修正)
        kohaku_MM_local_fixesContextPolyToolsMM("contextPolyToolsFaceMM");
        kohaku_MM_local_fixesContextPolyToolsMM("contextPolyToolsObjectMM");
    }
    { // Hook into Script Editor's popUpMenu
        string $owner = "Kohaku";
        string $proc = "verifyCommandPopupMenus";
        string $hook = $owner + "_MM_hookTo" + $proc;
        string $searchStringArray[] = {"",""};
        string $addStringArray[] = {"",""};
        string $positionFlgArray[] = {"", ""};
        $searchStringArray[0] = "}*";
        $addStringArray[0]= "    callbacks -ec -h \"" + $hook + "\";";
        $positionFlgArray[0] = "before";
        $searchStringArray[1] = "*for ($control in $gCommandExecuter) {*";
        $addStringArray[1] = "				if(!`menuItem -ex $gCommandPopupMenus[$index]`){$index++;continue;}";
        $positionFlgArray[1] = "after";
        kohaku_MM_local_changeProc $proc $searchStringArray $addStringArray $positionFlgArray; // Hook
        callbacks -cc -h $hook -o $owner;
        string $callback = "Kohaku_MM_scriptEditorPop";
        callbacks -ac $callback -h $hook -o $owner;
    }
    { // ShelfButtonのpopupMenuのPrefs_が存在しているか
        string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
        string $prefsLabelArray[];
        for($shelfButton in $shelfButtonArray){
            string $label = `shelfButton -query -label $shelfButton`;
            if(`gmatch $label "Kohaku Marking Menu Prefs_*"`) appendStringArray($prefsLabelArray, {$label}, 1);
        }
        for($shelfButton in $shelfButtonArray){
            string $targetPopupMenu;
            string $popupMenuArray[] = `shelfButton -query -popupMenuArray $shelfButton`;
            for($popupMenu in $popupMenuArray){
                if(`popupMenu -query -button $popupMenu` == 3
                    && !`popupMenu -query -altModifier $popupMenu`
                    && !`popupMenu -query -ctrlModifier $popupMenu`
                    && !`popupMenu -query -shiftModifier $popupMenu`){
                    $targetPopupMenu = $popupMenu;
                    break;
                }
            }
            string $menuItemArray[] = `popupMenu -query -itemArray $targetPopupMenu`;
            string $targetMenuItemArray[];
            for($menuItem in $menuItemArray){
                string $label = `menuItem -query -label $menuItem`;
                if(`gmatch $label "Prefs_*"`){
                    $label = `match "^[^ ]+" $label`;
                    if(stringArrayFind(("Kohaku Marking Menu " + $label), 0, $prefsLabelArray) == -1){
                        appendStringArray($targetMenuItemArray, {$menuItem}, 1);
                    }
                }
            }
            for($targetMenuItem in $targetMenuItemArray) deleteUI -menuItem $targetMenuItem;
        }
    }
    { // $gKohaku_MM_selectedPrefsのshelfButtonが存在するか
        if($gKohaku_MM_selectedPrefs != ""){
            string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
            int $selectedPrefsFlg = false;
            for($shelfButton in $shelfButtonArray){
                if(`shelfButton -query -label $shelfButton` == ("Kohaku Marking Menu Prefs_" + $gKohaku_MM_selectedPrefs)){
                    $selectedPrefsFlg = true;
                    break;
                }
            }
            if($selectedPrefsFlg == false){
                $gKohaku_MM_selectedPrefs = "";
                Kohaku_MM_local_recordDefaultPrefsToShelfButton();
            }
        }
    }
    if($gKohaku_MM_selectedPrefs != "") kohaku_MM_local_markingPrefs($gKohaku_MM_selectedPrefs); // Marking Prefs
    { // Shelf buttonの親にイベントフィルターを付ける
        string $shelfButtonArray[] = `shelfLayout -query -childArray "Kohaku_ExitMarkingMenuCommand"`;
        string $targetShelfButton;
        for($shelfButton in $shelfButtonArray){
            if(`shelfButton -query -label $shelfButton` == "Kohaku Marking Menu Prefs"){
                $targetShelfButton = $shelfButton;
                break;
            }
        }
        if($targetShelfButton == ""){
            $targetShelfButton = Kohaku_MM_recordMainOrSubShelfToPrefsShelfButton("", "Main", 0);
            $targetShelfButton = `match "[^|]+$" $targetShelfButton`;
        }
        string $melCmd = "evalDeferred(\"source \\\"kohaku_markingMenu\\\"\")";
        string $cmd = "try:\n"
                    + "    from PySide6.QtCore import QEvent, QObject\n"
                    + "    from PySide6.QtWidgets import QBoxLayout, QPushButton\n"
                    + "    from PySide6.QtGui import QKeyEvent\n"
                    + "    from shiboken6 import wrapInstance\n"
                    + "except:\n"
                    + "    from PySide2.QtCore import QEvent, QObject\n"
                    + "    from PySide2.QtWidgets import QBoxLayout, QPushButton\n"
                    + "    from shiboken2 import wrapInstance\n"
                    + "from maya.OpenMayaUI import MQtUtil\n"
                    + "from maya import mel\n"
                    + "class Kohaku_MM_ShelfFilterClass(QObject):\n"
                    + "    def eventFilter(self, watched: QObject, event: QEvent):\n"
                    + "        if event.type() == QEvent.ChildPolished or event.type() == QEvent.ChildRemoved:\n"
                    + "            mel.eval(\""+ `encodeString $melCmd` + "\")\n"
                    + "        return False\n"
                    + "def kohaku_MM_main():\n"
                    + "    ptr = MQtUtil.findControl(\"" +  $targetShelfButton + "\")\n"
                    + "    qPushButton = wrapInstance(int(ptr), QPushButton)\n"
                    + "    parent = qPushButton.parent()\n"
                    + "    parent.removeEventFilter(kohaku_MM_shelfFilter)\n"
                    + "    parent.installEventFilter(kohaku_MM_shelfFilter)\n"
                    + "kohaku_MM_shelfFilter = Kohaku_MM_ShelfFilterClass()\n"
                    + "kohaku_MM_main()\n"
                    + "del kohaku_MM_main"
                    ;
       python($cmd);
    }
    { // PanelをTear Offした場合
        string $owner = "Kohaku";
        string $proc = "ModelEdMenu";
        string $hook = $owner + "_MM_hookTo" + $proc;
        string $searchStringArray[] = {"*regular popup mappings*"};
        string $addStringArray[] = {""};
        $addStringArray[0]= "        callbacks -executeCallbacks -hook \"" + $hook + "\";";
        string $positionFlgArray[] = {"before"};
        kohaku_MM_local_changeProc $proc $searchStringArray $addStringArray $positionFlgArray; // Hook
        callbacks -clearCallbacks -hook $hook -owner $owner;
        string $callback = "evalDeferred \"source \\\"kohaku_markingMenu\\\"\"";
        callbacks -addCallback $callback -hook $hook -owner $owner;
    }
    { // Edit marking menu postMenuCommand in model panel
        string $modelPanelArray[] = `getPanel -type modelPanel`;
        string $menuNameArray[] = {"ObjectPop", "ConvertPop", "CommandPop", "ToolOptionsPop"};
        string $targetProcArray[] = {"buildObjectMenuItemsNow", "buildConvertMM", "contextToolsMM", "buildToolOptionsMM"};
        string $addProcArray[] = {"Kohaku_MM_editObjectSelectionMask(\"#1\");\n", "", "", ""}; // #1 : popupMenuFullPath
        string $existMarkingMenuCmdFlgArray[] = {"", "Ctrl", "Shift", "CtrlShift"};
        for($panelName in $modelPanelArray){
            { // 存在して変更済みか
                string $menuName = $panelName + $menuNameArray[0];
                if(!`menu -exists $menuName`) continue;
                string $orignPmCmd = `menu -query -postMenuCommand $menuName`;
                if(size(`match "kohaku_MM" $orignPmCmd`) != 0) continue;
            }
            int $index = 0;
            for($menuName in $menuNameArray){
                string $orignPmCmd = `menu -q -pmc ($panelName + $menuName)`;
                string $pmCmd = $orignPmCmd + ";\n"
                              + $addProcArray[$index]
                              + "kohaku_MM_setExistMarkingMenuCommand(\"" + $existMarkingMenuCmdFlgArray[$index ] + "\");\n"
                              + "python(\"kohaku_MM_setMarkingMenuEventFilter(\\\"#1\\\")\");\n"
                              + "Kohaku_MM_changeMenuToSubMenu(\"#1\", \"" + $targetProcArray[$index] + "\")";
                popupMenu -e -pmc $pmCmd ($panelName + $menuName);
                $index++;
            }
            { // Alt + Shift marking menu
                string $postMenuCmd = "python(\"kohaku_MM_setMarkingMenuEventFilter(\\\"#1\\\")\");\n"
                                    + "kohaku_MM_setExistMarkingMenuCommand(\"AltShift\");\n"
                                    + "Kohaku_MM_etcCommandPop(\"#1\")"
                                    ;
                kohaku_MM_local_buildModelEditorPopupMenu(
                    $panelName,
                    "Kohaku_MM_etcCommandPop",
                    $postMenuCmd
                    , 3, true, false, true, true
                );
            }
            // Ctrl + Alt + Shift marking menu
            string $postMenuCmd = "python(\"kohaku_MM_setMarkingMenuEventFilter(\\\"#1\\\")\");\n"
                                + "kohaku_MM_setExistMarkingMenuCommand(\"CtrlAltShift\");\n"
                                + "Kohaku_MM_shelfPop(\"#1\");\n"
                                + "Kohaku_MM_deleteMenuItemAndCreateSubMenu("
                                +     "\"#1\""
                                +     ", \"Kohaku_MM_shelfPop\""
                                +     ", {\"\"}"
                                +     ", \"Kohaku_MM_shelfPop\""
                                +     ", on"
                                + ")"
                                ;
            kohaku_MM_local_buildModelEditorPopupMenu($panelName, "Kohaku_MM_shelfPop", $postMenuCmd, 3, true, true, true, true);
            // Alt + Shift + Ctrl Left Click PopupMenu
            //kohaku_MM_local_buildModelEditorPopupMenu($panelName, "Kohaku_MM_testMenu", "Kohaku_MM_testMenu(\"#1\")", 1, true, true, true, true);
        }
    }
}
/* memo
variable = (expression) ? TrueValue : FalseValue
*/
```
を
C:\Users\ユーザー名\Documents\maya\scripts
に保存
　
```
source "kohaku_markingMenu";
```
を実行、もしくは
C:\Users\ユーザー名\Documents\maya\scripts
に
userSetup.mel
を作成して
```
evalDeferred "source \"kohaku_markingMenu\"";
```
を記入してください。

-----------------------------------------
農業と兼業で出来る在宅お仕事募集中。
作業できるのは、夜、雨の日、農閑期（冬）です。