code:
//=============================================================================
// Yanfly Engine Plugins - Message Core Extension - Backlog
// YEP_X_MessageBacklog.js
// Translate to Japanese : munokura.tk
//=============================================================================

var Imported = Imported || {};
Imported.YEP_X_MessageBacklog = true;

var Yanfly = Yanfly || {};
Yanfly.MsgBacklog = Yanfly.MsgBacklog || {};
Yanfly.MsgBacklog.version = 1.01;

//=============================================================================
 /*:
 * @plugindesc v1.01 (Requires YEP_MessageCore.js) Add a message backlog
 * function to your game's message system!
 * @author Yanfly Engine Plugins
 *
 * @help
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * This plugin requires the following plugins:
 * - YEP_MessageCore
 *
 * * Note: If you have any Extended Message Pack plugins from the YEP library,
 * place this plugin under those entries in the plugin list.
 *
 * It's not uncommon for RPG's to have a message backlog, an in-game tool for
 * the player to review any and all dialogue he/she has encountered previously.
 * This tool can be helpful in case a player would accidentally skip some
 * dialogue and/or would like to revisit what kind of messages were made before
 * making a decision during an important moment.
 *
 * This plugin creates a message backlog system for your game's message system.
 * Upon pressing 'Shift' (or any other button you desire) during a message, the
 * player can open up a Backlog window to review over the last 20 encountered
 * messages (number of stored messages can be modified within the parameters).
 * These saved messages can also include any choices from the choice lists they
 * have selected, any numbers they may have inputted, or items they selected
 * from special events.
 *
 * Now, your players can go forward, knowing full well they have little to
 * worry about in case they've missed any messages.
 *
 * ============================================================================
 * Disabled Text Codes
 * ============================================================================
 *
 * Due to the nature of some text codes, some of them are disabled for the
 * message log. Most of the default RPG Maker MV text codes will work, but some
 * custom ones added through the Message Core or Extension Packs are disabled
 * for various reasons. Here is a list of those disabled message codes:
 *
 *    RPG Maker MV Default:
 *    \{          Changes to font sizes cause errors in the backlog.
 *    \}          Changes to font sizes cause errors in the backlog.
 *
 *    Message Core:
 *    \AF[x]      Face graphics aren't displayed in the backlog.
 *    \PF[x]      Face graphics aren't displayed in the backlog.
 *    \FS[X]      Changes to font sizes cause errors in the backlog.
 *
 *    \PY[X]      While this works, it is known to cause some problems.
 *
 *    Extended Message Pack 1:
 *    \LSON       Letter sounds are disabled for the backlog.
 *    \LSOFF      Letter sounds are disabled for the backlog.
 *    \LSR        Letter sounds are disabled for the backlog.
 *    \FACEINDEX  Face graphics aren't displayed in the backlog.
 *    \MSGPOSX    Backlog does not change message window size.
 *    \MSGPOSY    Backlog does not change message window size.
 *    \MSGEVENT   Backlog does not change message window size.
 *    \MSGACTOR   Backlog does not change message window size.
 *    \MSGPARTY   Backlog does not change message window size.
 *    \MSGENEMY   Backlog does not change message window size.
 *    \AUTOEVENT  Backlog does not change message window size.
 *    \AUTOACTOR  Backlog does not change message window size.
 *    \AUTOPARTY  Backlog does not change message window size.
 *    \AUTOENEMY  Backlog does not change message window size.
 *    \MSGROWS    Backlog does not change message window size.
 *    \MSGWIDTH   Backlog does not change message window size.
 *    \AUTO       Backlog does not change message window size.
 *    \MSGRESET   Backlog does not change message window size.
 *
 *    Extended Message Pack 2:
 *    - Quantity, Actor, and Enemy text codes will be converted before added.
 *    This is so the data made will be localized instead of current.
 *
 * ============================================================================
 * Plugin Commands
 * ============================================================================
 *
 * The following plugin commands can be used to alter various settings
 * regarding the Message Backlog.
 *
 * Plugin Command:
 *
 *   EnableMessageBacklog
 *   DisableMessageBacklog
 *   - This enables/disables the message backlog from being playeraccessed.
 *
 *   EnableMessageLogging
 *   DisableMessageLogging
 *   - If enabled, new messages will be recorded to the backlog.
 *   If disabled, they won't be recorded.
 *
 *   OpenMessageBacklog
 *   - This will forcefully open the message backlog if done on the map scene.
 *   (Highly recommended to be used with Button Common Events)
 *
 * ============================================================================
 * Changelog
 * ============================================================================
 *
 * Version 1.01:
 * - Message Backlog now removes more text codes regarding Letter Sounds.
 *
 * Version 1.00:
 * - Finished Plugin!
 *
 * ============================================================================
 * End of Helpfile
 * ============================================================================
 *
 * @param ---Backlog Key---
 * @default
 *
 * @param LogKeyButton
 * @text Backlog Key Button
 * @parent ---Backlog Key---
 * @type combo
 * @option tab
 * @option shift
 * @option control
 * @option pageup
 * @option pagedown
 * @desc When pressed during a message, this will open up
 * the Backlog window.
 * @default shift
 *
 * @param EnableLogKey
 * @text Enable Backlog Key
 * @parent ---Backlog Key---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Enable Backlog button for your messages by default?
 * NO - false     YES - true
 * @default true
 *
 * @param ---Settings---
 * @default
 *
 * @param DefaultLogging
 * @text Default Logging
 * @parent ---Settings---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Log all messages by default?
 * NO - false     YES - true
 * @default true
 *
 * @param LogSpecialInput
 * @text Log Special Inputs
 * @parent ---Settings---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Log the special inputs made by the player?
 * NO - false     YES - true
 * @default true
 *
 * @param SpecialInputFmt
 * @text Special Input Format
 * @parent LogSpecialInput
 * @desc Format used to display special input text in backlog.
 * %1 - The text used in the selected choice.
 * @default »%1
 *
 * @param MaximumEntries
 * @text Maximum Entries
 * @parent ---Settings---
 * @type number
 * @min 1
 * @desc This is the maximum number of backlog entries.
 * If more than max are added, oldest entry will be removed.
 * @default 20
 *
 * @param ScrollBarEnabled
 * @text Scroll Bar Enabled
 * @parent ---Settings---
 * @type boolean
 * @on SHOW
 * @off HIDE
 * @desc Show a scroll bar for the message log?
 * HIDE - false     SHOW - true
 * @default true
 *
 * @param ScrollBarColor
 * @text Scroll Bar Color
 * @parent ScrollBarEnabled
 * @type number
 * @min 0
 * @max 31
 * @desc This is the text color used for the scroll bar.
 * @default 0
 *
 * @param ScrollBarSpriteCode
 * @text Sprite Code
 * @parent ScrollBarEnabled
 * @type note
 * @desc This is the code used for the scroll bar's sprite.
 * Edit this if you wish to customize it for your game.
 * @default "// Establish basic measurements\nvar padding = backlogWindow.standardPadding();\nvar width = padding / 2;\nvar height = Graphics.boxHeight;\n\n// Calculate number of visible rows\nvar visibleRows = backlogWindow.height - padding * 2;\nvisibleRows = Math.floor(visibleRows / backlogWindow.lineHeight());\nif (visibleRows < backlogWindow.maxItems()) {\n  height *= visibleRows / Math.max(1, backlogWindow.maxItems());\n}\n\n// Calculate the size of a basic scrolling increment\nvar max = Math.floor(Math.max(1, backlogWindow.maxItems()) / backlogWindow.maxCols()) - 1;\nthis._increment = Graphics.boxHeight / Math.max(1, max);\n\n// Generate the bitmap\nthis.bitmap = new Bitmap(width, height);\nthis.bitmap.fillAll(backlogWindow.textColor(scrollBarColor));"
 *
 * @param ScrollSpeed
 * @text Scroll Speed
 * @parent ---Settings---
 * @type number
 * @min 0
 * @desc This is the scroll speed used for backlog.
 * Lower numbers are faster. Higher numbers are slower.
 * @default 4
 *
 * @param ScrollWrap
 * @text Scroll Wrap
 * @parent ---Settings---
 * @type boolean
 * @on YES
 * @off NO
 * @desc If player is at the bottom log entry, hitting down
 * would wrap the player back to the top. Enable this?
 * @default true
 *
 * @param ---Visual---
 * @default
 *
 * @param BackgroundType
 * @text Background Type
 * @parent ---Visual---
 * @type select
 * @option Window
 * @value 0
 * @option Dimmed
 * @value 1
 * @option Picture
 * @value 2
 * @option Transparent
 * @value 3
 * @desc What kind of background type do you wish to use
 * for the message backlog window?
 * @default 1
 *
 * @param BackOpacity
 * @text Back Opacity
 * @parent ---Visual---
 * @type number
 * @min 0
 * @max 255
 * @desc If you are using a Window background type,
 * adjust this number to set the window's back opacity.
 * @default 192
 *
 * @param DimColor1
 * @text Dim Color 1
 * @parent ---Visual---
 * @desc If you are using a Dimmed background type,
 * adjust the first color here. Default: rgba(0, 0, 0, 0.6)
 * @default rgba(0, 0, 0, 0.8)
 *
 * @param DimColor2
 * @text Dim Color 2
 * @parent ---Visual---
 * @desc If you are using a Dimmed background type,
 * adjust the first color here. Default: rgba(0, 0, 0, 0)
 * @default rgba(0, 0, 0, 0.8)
 *
 * @param Picture
 * @parent ---Visual---
 * @type file
 * @dir img/pictures/
 * @require 1
 * @desc If you are using a Picture background type,
 * select a picture to use for your background.
 * @default
 *
 * @param PictureOpacity
 * @text Picture Opacity
 * @parent ---Visual---
 * @type number
 * @min 0
 * @max 255
 * @desc If you are using a Picture background type,
 * adjust this number to set the picture's opacity.
 * @default 255
 *
 * @param PictureStretch
 * @text Picture Stretch
 * @parent ---Visual---
 * @type boolean
 * @on Stretch
 * @off Don't Stretch
 * @desc If the picture used for the background is smaller than
 * the screen, stretch it to fit the screen?
 * @default true
 *
 */
 /*:ja
 * @plugindesc v1.01 (要YEP_MessageCore.js) メッセージシステムにメッセージバックログ機能を追加します。
 * @author Yanfly Engine Plugins
 *
 * @help
 * 翻訳:ムノクラ
 * https://munokura.tk/
 * https://twitter.com/munokura/
 *
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * このプラグインはには YEP_MessageCore プラグインが必要です。
 *
 * 注:Extended Message Packプラグインがある場合、
 * このプラグインをプラグインリストのそれらのエントリの下に配置します。
 *
 * RPGがメッセージバックログを持つことは珍しいことではありません。
 * プレイヤーが以前に遭遇したすべての対話を確認するためのゲーム内ツールです。
 * このツールは、プレイヤーが誤って会話をスキップしたり、
 * 重要な瞬間に決定を下す前に過去のメッセージを再確認したい場合に役立ちます。
 *
 * このプラグインはあなたのゲームのメッセージシステム用の
 * メッセージバックログシステムを作成します。
 * ※「メッセージ中に」'Shift'（またはあなたが望む他のボタン）を押すと、
 * プレイヤーはバックログウィンドウを開いて
 * 直近20個のメッセージを見直すことができます
 * （保存されたメッセージの数はパラメータ内で変更できます）。
 * これらの保存されたメッセージには、選択リストからの選択、
 * 入力した番号、または特別なイベントから選択した項目を含めることもできます。
 *
 * プレイヤーはメッセージを見逃してしまったとしても、
 * 心配する必要がほとんどないことを十分に知っているので、
 * 先に進むことができます。
 *
 * ============================================================================
 * Disabled Text Codes
 * ============================================================================
 *
 * 一部のテキストコードの性質上、
 * それらの一部はメッセージログに対して無効になっています。
 * RPGツクールMVのデフォルトのテキストコードの大部分は機能しますが、
 * Message Core または Extension Pack を通じて追加されたカスタムコードは
 * さまざまな理由で無効になっています。
 * これらの無効にされたメッセージコードのリストは以下です。
 *
 *    RPG Maker MV Default:
 *    \{          フォントサイズを変更すると、バックログにエラーが発生します。
 *    \}          フォントサイズを変更すると、バックログにエラーが発生します。
 *
 *    Message Core:
 *    \AF[x]      バックログには顔グラフィックは表示されません。
 *    \PF[x]      バックログには顔グラフィックは表示されません。
 *    \FS[X]      フォントサイズを変更すると、バックログにエラーが発生します。
 *
 *    \PY[X]      一応動作しますが、
 *                いくつかの問題を引き起こすことが分かっています。
 *
 *    Extended Message Pack 1:
 *    \LSON       バックログのレターサウンドは無効になっています。
 *    \LSOFF      バックログのレターサウンドは無効になっています。
 *    \LSR        バックログのレターサウンドは無効になっています。
 *    \FACEINDEX  バックログには顔グラフィックは表示されません。
 *    \MSGPOSX    バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGPOSY    バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGEVENT   バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGACTOR   バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGPARTY   バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGENEMY   バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTOEVENT  バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTOACTOR  バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTOPARTY  バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTOENEMY  バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGROWS    バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGWIDTH   バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTO       バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGRESET   バックログはメッセージウィンドウサイズを変更しません。
 *
 *    Extended Message Pack 2:
 *    - 数、アクター、敵のテキストコードは追加前に変換されます。
 *    作成されたデータが最新のデータではなくローカライズされるためです。
 *
 * ============================================================================
 * Plugin Commands
 * ============================================================================
 *
 * 以下のプラグインコマンドを使用して、
 * メッセージバックログに関するさまざまな設定を変更できます。
 *
 * プラグインコマンド:
 *
 *   EnableMessageBacklog
 *   DisableMessageBacklog
 *   - メッセージバックログが再生されないようにします。
 *
 *   EnableMessageLogging
 *   DisableMessageLogging
 *   - 有効にすると、新しいメッセージがバックログに記録されます。
 *   無効にした場合、それらは記録されません。
 *
 *   OpenMessageBacklog
 *   - マップシーンでこれを行うと、メッセージバックログが強制的に開かれます。
 *   （ボタンコモンイベントとの併用を強く推奨）
 *
 * ============================================================================
 * Changelog
 * ============================================================================
 *
 * Version 1.01:
 * - Message Backlog now removes more text codes regarding Letter Sounds.
 *
 * Version 1.00:
 * - Finished Plugin!
 *
 * ============================================================================
 * End of Helpfile
 * ============================================================================
 *
 * @param ---バックログキー---
 * @default
 *
 * @param LogKeyButton
 * @text Backlog Key Button
 * @parent ---バックログキー---
 * @type combo
 * @option tab
 * @option shift
 * @option control
 * @option pageup
 * @option pagedown
 * @desc メッセージ中に押すと、バックログウィンドウが開きます。
 * @default shift
 *
 * @param EnableLogKey
 * @text Enable Backlog Key
 * @parent ---バックログキー---
 * @type boolean
 * @on 有効
 * @off 無効
 * @desc メッセージのバックログボタンのデフォルト設定
 * 無効 - false     有効 - true
 * @default true
 *
 * @param ---設定---
 * @default
 *
 * @param DefaultLogging
 * @text Default Logging
 * @parent ---設定---
 * @type boolean
 * @on すべて記録
 * @off 記録しない
 * @desc メッセージのデフォルト記録設定
 * 記録しない - false     すべて記録 - true
 * @default true
 *
 * @param LogSpecialInput
 * @text Log Special Inputs
 * @parent ---設定---
 * @type boolean
 * @on YES
 * @off NO
 * @desc プレイヤーによる特別な入力を記録しますか？
 * NO - false     YES - true
 * @default true
 *
 * @param SpecialInputFmt
 * @text Special Input Format
 * @parent LogSpecialInput
 * @desc バックログに特別な入力テキストを表示するために使用される形式。
 * %1 - 選択肢で選択したテキスト
 * @default »%1
 *
 * @param MaximumEntries
 * @text Maximum Entries
 * @parent ---設定---
 * @type number
 * @min 1
 * @desc バックログの記録最大数。最大数を超えて追加された場合、最も古いエントリが削除されます。
 * @default 20
 *
 * @param ScrollBarEnabled
 * @text Scroll Bar Enabled
 * @parent ---設定---
 * @type boolean
 * @on 表示
 * @off 非表示
 * @desc メッセージログのスクロールバー表示設定
 * 非表示 - false     表示 - true
 * @default true
 *
 * @param ScrollBarColor
 * @text Scroll Bar Color
 * @parent ScrollBarEnabled
 * @type number
 * @min 0
 * @max 31
 * @desc スクロールバーのテキスト色
 * @default 0
 *
 * @param ScrollBarSpriteCode
 * @text Sprite Code
 * @parent ScrollBarEnabled
 * @type note
 * @desc これはスクロールバーのスプライトに使用されるコードです。
 * カスタマイズしたい場合、これを編集してください。
 * @default "// Establish basic measurements\nvar padding = backlogWindow.standardPadding();\nvar width = padding / 2;\nvar height = Graphics.boxHeight;\n\n// Calculate number of visible rows\nvar visibleRows = backlogWindow.height - padding * 2;\nvisibleRows = Math.floor(visibleRows / backlogWindow.lineHeight());\nif (visibleRows < backlogWindow.maxItems()) {\n  height *= visibleRows / Math.max(1, backlogWindow.maxItems());\n}\n\n// Calculate the size of a basic scrolling increment\nvar max = Math.floor(Math.max(1, backlogWindow.maxItems()) / backlogWindow.maxCols()) - 1;\nthis._increment = Graphics.boxHeight / Math.max(1, max);\n\n// Generate the bitmap\nthis.bitmap = new Bitmap(width, height);\nthis.bitmap.fillAll(backlogWindow.textColor(scrollBarColor));"
 *
 * @param ScrollSpeed
 * @text Scroll Speed
 * @parent ---設定---
 * @type number
 * @min 0
 * @desc バックログに使用されるスクロール速度。 数値が小さいと速く大きいと遅くなります。
 * @default 4
 *
 * @param ScrollWrap
 * @text Scroll Wrap
 * @parent ---設定---
 * @type boolean
 * @on 有効
 * @off 無効
 * @desc 一番下のログエントリを選択している時、下を押すとエントリの一番上に戻る設定
 * @default true
 *
 * @param ---ビジュアル---
 * @default
 *
 * @param BackgroundType
 * @text Background Type
 * @parent ---ビジュアル---
 * @type select
 * @option ウィンドウ
 * @value 0
 * @option ぼかし
 * @value 1
 * @option 画像
 * @value 2
 * @option 透明
 * @value 3
 * @desc バックログウィンドウの背景
 * @default 1
 *
 * @param BackOpacity
 * @text Back Opacity
 * @parent ---ビジュアル---
 * @type number
 * @min 0
 * @max 255
 * @desc ウィンドウの背面の不透明度
 * @default 192
 *
 * @param DimColor1
 * @text Dim Color 1
 * @parent ---ビジュアル---
 * @desc ぼかし背景の色1 Default: rgba(0, 0, 0, 0.6)
 * @default rgba(0, 0, 0, 0.8)
 *
 * @param DimColor2
 * @text Dim Color 2
 * @parent ---ビジュアル---
 * @desc ぼかし背景の色2 Default: rgba(0, 0, 0, 0)
 * @default rgba(0, 0, 0, 0.8)
 *
 * @param Picture
 * @parent ---ビジュアル---
 * @type file
 * @dir img/pictures/
 * @require 1
 * @desc 画像背景の使用画像
 * @default
 *
 * @param PictureOpacity
 * @text Picture Opacity
 * @parent ---ビジュアル---
 * @type number
 * @min 0
 * @max 255
 * @desc 画像背景の不透明度
 * @default 255
 *
 * @param PictureStretch
 * @text Picture Stretch
 * @parent ---ビジュアル---
 * @type boolean
 * @on 拡大する
 * @off 拡大しない
 * @desc 背景画像が画面より小さい場合、画面に合わせて拡大
 * @default true
 *
 */
//=============================================================================

if (Imported.YEP_MessageCore) {

//=============================================================================
// Parameter Variables
//=============================================================================

Yanfly.Parameters = PluginManager.parameters('YEP_X_MessageBacklog');
Yanfly.Param = Yanfly.Param || {};

Yanfly.Param.MsgBacklogKeyButton = String(Yanfly.Parameters['LogKeyButton']);
Yanfly.Param.MsgBacklogEnableKey = String(Yanfly.Parameters['EnableLogKey']);
Yanfly.Param.MsgBacklogEnableKey = eval(Yanfly.Param.MsgBacklogEnableKey);

Yanfly.Param.MsgBacklogDefaultLog = String(Yanfly.Parameters['DefaultLogging']);
Yanfly.Param.MsgBacklogDefaultLog = eval(Yanfly.Param.MsgBacklogDefaultLog);
Yanfly.Param.MsgBacklogSpcInput = String(Yanfly.Parameters['LogSpecialInput']);
Yanfly.Param.MsgBacklogSpcInput = eval(Yanfly.Param.MsgBacklogSpcInput);
Yanfly.Param.MsgBacklogSpcFmt = String(Yanfly.Parameters['SpecialInputFmt']);
Yanfly.Param.MsgBacklogMaxEntries = Number(Yanfly.Parameters['MaximumEntries']);
Yanfly.Param.MsgBacklogScrBarEn = String(Yanfly.Parameters['ScrollBarEnabled']);
Yanfly.Param.MsgBacklogScrBarEn = eval(Yanfly.Param.MsgBacklogScrBarEn);
Yanfly.Param.MsgBacklogScrBarCol = Number(Yanfly.Parameters['ScrollBarColor']);
Yanfly.Param.MsgBacklogScrBarSpriteCode =
  JSON.parse(Yanfly.Parameters['ScrollBarSpriteCode']);
Yanfly.Param.MsgBacklogScrollSpd = Number(Yanfly.Parameters['ScrollSpeed']);
Yanfly.Param.MsgBacklogScrollWrap = String(Yanfly.Parameters['ScrollWrap']);
Yanfly.Param.MsgBacklogScrollWrap = eval(Yanfly.Param.MsgBacklogScrollWrap);

Yanfly.Param.MsgBacklogBgType = Number(Yanfly.Parameters['BackgroundType']);
Yanfly.Param.MsgBacklogBackOpacity = Number(Yanfly.Parameters['BackOpacity']);
Yanfly.Param.MsgBacklogDimColor1 = String(Yanfly.Parameters['DimColor1']);
Yanfly.Param.MsgBacklogDimColor2 = String(Yanfly.Parameters['DimColor2']);
Yanfly.Param.MsgBacklogPicture = String(Yanfly.Parameters['Picture']);
Yanfly.Param.MsgBacklogPicOpacity = Number(Yanfly.Parameters['PictureOpacity']);
Yanfly.Param.MsgBacklogPicStretch = String(Yanfly.Parameters['PictureStretch']);
Yanfly.Param.MsgBacklogPicStretch = eval(Yanfly.Param.MsgBacklogPicStretch);

//=============================================================================
// Game_Temp
//=============================================================================

Game_Temp.prototype.isMessageBacklogOpened = function() {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    var win = SceneManager._scene._messageWindow;
    if (win._backlogWindow && win._backlogWindow.isOpenAndActive()) {
      return true;
    }
  }
  return false;
};

//=============================================================================
// Game_System
//=============================================================================

Yanfly.MsgBacklog.Game_System_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
  Yanfly.MsgBacklog.Game_System_initialize.call(this);
  this.initMessageBacklog();
};

Game_System.prototype.initMessageBacklog = function() {
  this._messageBacklog = [];
  this._messageBacklogKeyEnable = Yanfly.Param.MsgBacklogEnableKey;
  this._messageBacklogLoggingEnable = Yanfly.Param.MsgBacklogDefaultLog;
};

Game_System.prototype.addMessageBacklog = function(text) {
  if (!this.isMessageBacklogLoggingEnabled()) return;
  text = this.convertMessageBacklogText(text);
  this._messageBacklog.push(text);
  while (this._messageBacklog.length > Yanfly.Param.MsgBacklogMaxEntries) {
    this._messageBacklog.shift();
  }
};

Game_System.prototype.convertMessageBacklogText = function(text) {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    var win = SceneManager._scene._messageWindow._backlogWindow;
    if (win) text = win.convertMessageText(text);
  }
  return text;
};

Game_System.prototype.getMessageBacklog = function() {
  if (this._messageBacklog === undefined) this.initMessageBacklog();
  return this._messageBacklog;
};

Game_System.prototype.isMessageBacklogKeyEnabled = function() {
  if (this._messageBacklogKeyEnable === undefined) this.initMessageBacklog();
  return this._messageBacklogKeyEnable;
};

Game_System.prototype.setMessageBacklogKeyEnable = function(value) {
  if (this._messageBacklogKeyEnable === undefined) this.initMessageBacklog();
  this._messageBacklogKeyEnable = value;
};

Game_System.prototype.isMessageBacklogLoggingEnabled = function() {
  if (this._messageBacklogLoggingEnable === undefined) {
    this.initMessageBacklog();
  }
  return this._messageBacklogLoggingEnable;
};

Game_System.prototype.setMessageBacklogLoggingEnable = function(value) {
  if (this._messageBacklogLoggingEnable === undefined) {
    this.initMessageBacklog();
  }
  this._messageBacklogLoggingEnable = value;
};

//=============================================================================
// Game_Player
//=============================================================================

Yanfly.MsgBacklog.Game_Player_canMove = Game_Player.prototype.canMove;
Game_Player.prototype.canMove = function() {
  if ($gameTemp.isMessageBacklogOpened()) return false;
  return Yanfly.MsgBacklog.Game_Player_canMove.call(this);
};

//=============================================================================
// Game_Event
//=============================================================================

Yanfly.MsgBacklog.Game_Event_updateSelfMovement =
  Game_Event.prototype.updateSelfMovement;
Game_Event.prototype.updateSelfMovement = function() {
  if ($gameTemp.isMessageBacklogOpened()) return;
  Yanfly.MsgBacklog.Game_Event_updateSelfMovement.call(this);
};

//=============================================================================
// Game_Interpreter
//=============================================================================

Yanfly.MsgBacklog.Game_Interpreter_pluginCommand =
  Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
  Yanfly.MsgBacklog.Game_Interpreter_pluginCommand.call(this, command, args);
  // Plugin Commands
  if (command === 'EnableMessageBacklog') {
    $gameSystem.setMessageHideKeyEnable(true);

  } else if (command === 'DisableMessageBacklog') {
    $gameSystem.setMessageHideKeyEnable(false);

  } else if (command === 'EnableMessageLogging') {
    $gameSystem.setMessageBacklogLoggingEnable(true);

  } else if (command === 'DisableMessageLogging') {
    $gameSystem.setMessageBacklogLoggingEnable(false);

  } else if (command === 'OpenMessageBacklog') {
    if (SceneManager._scene instanceof Scene_Map) {
      var win = SceneManager._scene._messageWindow;
      if (win) win.openBacklogWindow();
    }

  // End
  }
};

//=============================================================================
// Scene_Map
//=============================================================================

Yanfly.MsgBacklog.Scene_Map_isMenuEnabled = Scene_Map.prototype.isMenuEnabled;
Scene_Map.prototype.isMenuEnabled = function() {
  if ($gameTemp.isMessageBacklogOpened()) return false;
  return Yanfly.MsgBacklog.Scene_Map_isMenuEnabled.call(this);
};

//=============================================================================
// Window_Message
//=============================================================================

Yanfly.MsgBacklog.Window_Message_createSubWindows =
  Window_Message.prototype.createSubWindows;
Window_Message.prototype.createSubWindows = function() {
  Yanfly.MsgBacklog.Window_Message_createSubWindows.call(this);
  this.createMessageBacklogWindow();
};

Window_Message.prototype.createMessageBacklogWindow = function() {
  this._backlogWindow = new Window_MessageBacklog();
  SceneManager._scene.addChild(this._backlogWindow);
};

Yanfly.MsgBacklog.Window_Message_isAnySubWindowActive =
  Window_Message.prototype.isAnySubWindowActive;
Window_Message.prototype.isAnySubWindowActive = function() {
  if (this._backlogWindow.active) return true;
  return Yanfly.MsgBacklog.Window_Message_isAnySubWindowActive.call(this);
};

Yanfly.MsgBacklog.Window_Message_startMessage =
  Window_Message.prototype.startMessage;
Window_Message.prototype.startMessage = function() {
  Yanfly.MsgBacklog.Window_Message_startMessage.call(this);
  $gameSystem.addMessageBacklog($gameMessage.allText());
};

Yanfly.MsgBacklog.Window_Message_updateInput =
  Window_Message.prototype.updateInput;
Window_Message.prototype.updateInput = function() {
  if (this.isAnySubWindowActive()) return true;
  this.updateBacklogInput();
  var value = Yanfly.MsgBacklog.Window_Message_updateInput.call(this);
  return value;
};

Window_Message.prototype.updateBacklogInput = function() {
  if (!this.pause) return;
  if (!$gameSystem.isMessageBacklogKeyEnabled()) return;
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this.openBacklogWindow();
  }
};

Window_Message.prototype.openBacklogWindow = function() {
  this._backlogWindow.fullActivate();
};

Window_Message.prototype.setReturnWindow = function(target) {
  this._backlogWindow.setReturnWindow(target);
};

//=============================================================================
// Window_ChoiceList
//=============================================================================

Yanfly.MsgBacklog.Window_ChoiceList_processHandling =
  Window_ChoiceList.prototype.processHandling;
Window_ChoiceList.prototype.processHandling = function() {
  if (this.isOpenAndActive()) this.updateBacklogInput();
  Yanfly.MsgBacklog.Window_ChoiceList_processHandling.call(this);
};

Window_ChoiceList.prototype.updateBacklogInput = function() {
  if (!$gameSystem.isMessageBacklogKeyEnabled()) return;
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this.openBacklogWindow();
  }
};

Window_ChoiceList.prototype.openBacklogWindow = function() {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    SceneManager._scene._messageWindow.setReturnWindow(this);
    SceneManager._scene._messageWindow.openBacklogWindow();
  }
};

Yanfly.MsgBacklog.Window_ChoiceList_callOkHandler =
  Window_ChoiceList.prototype.callOkHandler;
Window_ChoiceList.prototype.callOkHandler = function() {
  this.backlogAddSelectedChoice();
  Yanfly.MsgBacklog.Window_ChoiceList_callOkHandler.call(this);
};

Window_ChoiceList.prototype.backlogAddSelectedChoice = function() {
  if (!Yanfly.Param.MsgBacklogSpcInput) return;
  var fmt = Yanfly.Param.MsgBacklogSpcFmt;
  var text = fmt.format(this.commandName(this.index()));
  $gameSystem.addMessageBacklog(text);
};

//=============================================================================
// Window_NumberInput
//=============================================================================

Yanfly.MsgBacklog.Window_NumberInput_processHandling =
  Window_NumberInput.prototype.processHandling;
Window_NumberInput.prototype.processHandling = function() {
  if (this.isOpenAndActive()) this.updateBacklogInput();
  Yanfly.MsgBacklog.Window_NumberInput_processHandling.call(this);
};

Window_NumberInput.prototype.updateBacklogInput = function() {
  if (!$gameSystem.isMessageBacklogKeyEnabled()) return;
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this.openBacklogWindow();
  }
};

Window_NumberInput.prototype.openBacklogWindow = function() {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    SceneManager._scene._messageWindow.setReturnWindow(this);
    SceneManager._scene._messageWindow.openBacklogWindow();
  }
};

Yanfly.MsgBacklog.Window_NumberInput_processOk =
  Window_NumberInput.prototype.processOk;
Window_NumberInput.prototype.processOk = function() {
  this.backlogAddSelectedChoice();
  Yanfly.MsgBacklog.Window_NumberInput_processOk.call(this);
};

Window_NumberInput.prototype.backlogAddSelectedChoice = function() {
  if (!Yanfly.Param.MsgBacklogSpcInput) return;
  var fmt = Yanfly.Param.MsgBacklogSpcFmt;
  var text = fmt.format(Yanfly.Util.toGroup(this._number));
  $gameSystem.addMessageBacklog(text);
};

//=============================================================================
// Window_EventItem
//=============================================================================

Yanfly.MsgBacklog.Window_EventItem_processHandling =
  Window_EventItem.prototype.processHandling;
Window_EventItem.prototype.processHandling = function() {
  if (this.isOpenAndActive()) this.updateBacklogInput();
  Yanfly.MsgBacklog.Window_EventItem_processHandling.call(this);
};

Window_EventItem.prototype.updateBacklogInput = function() {
  if (!$gameSystem.isMessageBacklogKeyEnabled()) return;
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this.openBacklogWindow();
  }
};

Window_EventItem.prototype.openBacklogWindow = function() {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    SceneManager._scene._messageWindow.setReturnWindow(this);
    SceneManager._scene._messageWindow.openBacklogWindow();
  }
};

Yanfly.MsgBacklog.Window_EventItem_onOk = Window_EventItem.prototype.onOk;
Window_EventItem.prototype.onOk = function() {
  this.backlogAddSelectedChoice();
  Yanfly.MsgBacklog.Window_EventItem_onOk.call(this);
};

Window_EventItem.prototype.backlogAddSelectedChoice = function() {
  if (!Yanfly.Param.MsgBacklogSpcInput) return;
  var fmt = Yanfly.Param.MsgBacklogSpcFmt;
  var item = this.item();
  var text = fmt.format('\\i[' + item.iconIndex + ']' + item.name);
  $gameSystem.addMessageBacklog(text);
};

//=============================================================================
// Sprite_BacklogScroll
//=============================================================================

function Sprite_BacklogScroll() {
    this.initialize.apply(this, arguments);
}

Sprite_BacklogScroll.prototype = Object.create(Sprite.prototype);
Sprite_BacklogScroll.prototype.constructor = Sprite_BacklogScroll;

Sprite_BacklogScroll.prototype.initialize = function(target) {
  this._target = target;
  Sprite.prototype.initialize.call(this);
  this._target._scrollSprite = this;
  this.initMembers();
  this.createBitmap();
};

Sprite_BacklogScroll.prototype.initMembers = function() {
  this.anchor.x = 1;
  this.anchor.y = 0;
  this.x = Graphics.boxWidth;
  this.y = 0;
  this._increment = 1;
};

Sprite_BacklogScroll.prototype.createBitmap = function() {
  var scrollBarColor = Yanfly.Param.MsgBacklogScrBarCol;
  var backlogWindow = this._target;
  this._increment = 1;
  eval(Yanfly.Param.MsgBacklogScrBarSpriteCode);
};

Sprite_BacklogScroll.prototype.resize = function() {
  this.bitmap.clear();
  this.createBitmap();
};

Sprite_BacklogScroll.prototype.update = function() {
  Sprite.prototype.update.call(this);
  if (!this._target) return;
  this.updateOpacity();
  //this.updatePosition();
};

Sprite_BacklogScroll.prototype.updateOpacity = function() {
  this.opacity = this._target.isOpen() ? 255 : 0;
};

Sprite_BacklogScroll.prototype.updatePosition = function() {
  var target = this._target;
  if (!target.isOpen()) return;
  this.y = target.topRow() * this._increment;
};

//=============================================================================
// Window_MessageBacklog
//=============================================================================

function Window_MessageBacklog() {
    this.initialize.apply(this, arguments);
}

Window_MessageBacklog.prototype = Object.create(Window_Command.prototype);
Window_MessageBacklog.prototype.constructor = Window_MessageBacklog;

Window_MessageBacklog.prototype.initialize = function() {
  this._touchHold = 0;
  this._ready = false;
  Window_Command.prototype.initialize.call(this, 0, 0);
  this.createScrollSprite(this);
  this.setBackgroundType(Yanfly.Param.MsgBacklogBgType);
  this.deactivate();
  this.openness = 0;
  this._ready = true;
};

Window_MessageBacklog.prototype.createScrollSprite = function() {
  if (!Yanfly.Param.MsgBacklogScrBarEn) return;
  this._scrollSprite = new Sprite_BacklogScroll(this);
  this.addChild(this._scrollSprite);
};

Window_MessageBacklog.prototype.windowWidth = function() {
  return Graphics.boxWidth;
};

Window_MessageBacklog.prototype.windowHeight = function() {
  return Graphics.boxHeight;
};

Window_MessageBacklog.prototype.dimColor1 = function() {
  return Yanfly.Param.MsgBacklogDimColor1;
};

Window_MessageBacklog.prototype.dimColor2 = function() {
  return Yanfly.Param.MsgBacklogDimColor2;
};

Window_MessageBacklog.prototype.setBackgroundType = function(type) {
  Window_Base.prototype.setBackgroundType.call(this, type);
  if (type === 2) this.createBackgroundPicture();
};

Window_MessageBacklog.prototype.createBackgroundPicture = function() {
  var filename = Yanfly.Param.MsgBacklogPicture;
  if (filename === '') return;
  this._backgroundPicture = new Sprite();
  this._backgroundPicture.bitmap = ImageManager.loadPicture(filename, 0);
  SceneManager._scene.addChild(this._backgroundPicture);
  this._backgroundPicture.opacity = 0;
  this._backgroundPicture.anchor.x = 0.5;
  this._backgroundPicture.anchor.y = 0.5;
  this._backgroundPicture.x = Graphics.boxWidth / 2;
  this._backgroundPicture.y = Graphics.boxHeight / 2;
};

Window_MessageBacklog.prototype.setBgPictureOpacity = function(opacity) {
  this._backgroundPicture.opacity = opacity;

  this.stretchBgPicture();
};

Window_MessageBacklog.prototype.stretchBgPicture = function() {
  if (!Yanfly.Param.MsgBacklogPicStretch) return;
  if (this._backgroundPicture.width < Graphics.boxWidth) {
    var rate = Graphics.boxWidth / this._backgroundPicture.width;
    this._backgroundPicture.scale.x = rate;
  }
  if (this._backgroundPicture.height < Graphics.boxHeight) {
    var rate = Graphics.boxHeight / this._backgroundPicture.height;
    this._backgroundPicture.scale.y = rate;
  }
};

Window_MessageBacklog.prototype.standardFontFace = function() {
  return Window_Message.prototype.standardFontFace.call(this);
};

Window_MessageBacklog.prototype.standardFontSize = function() {
  return Window_Message.prototype.standardFontSize.call(this);
};

Window_MessageBacklog.prototype.standardBackOpacity = function() {
  return Yanfly.Param.MsgBacklogBackOpacity;
};

Window_MessageBacklog.prototype.makeFontBigger = function() {
};

Window_MessageBacklog.prototype.makeFontSmaller = function() {
};

Window_MessageBacklog.prototype.select = function(index) {
};

Window_MessageBacklog.prototype.moveSelect = function(index) {
  Window_Command.prototype.select.call(this, index);
  if (this._scrollSprite) this._scrollSprite.updatePosition();
};

Window_MessageBacklog.prototype.deselect = function() {
  this.moveSelect(-1);
};

Window_MessageBacklog.prototype.processHandling = function() {
  if (!this.isOpenAndActive()) return;
  Window_Command.prototype.processHandling.call(this);
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this.processCancel();
  }
};

Window_MessageBacklog.prototype.setReturnWindow = function(target) {
  this._returnWindow = target;
  this._returnWindow.deactivate();
};

Window_MessageBacklog.prototype.fullActivate = function() {
  this.updateInputData();
  Input.clear();
  TouchInput.clear();
  this.refresh();
  this.activate();
  this.openness = 255;
  this.moveSelect(this.maxItems() - 1);
  if (this._scrollSprite) this._scrollSprite.resize();
  if (this._backgroundPicture) {
    this.setBgPictureOpacity(Yanfly.Param.MsgBacklogPicOpacity);
  }
};

Window_MessageBacklog.prototype.processOk = function() {
  SoundManager.playOk();
  this.fullDeactivate();
};

Window_MessageBacklog.prototype.isCancelEnabled = function() {
  return true;
};

Window_MessageBacklog.prototype.processCancel = function() {
  SoundManager.playCancel();
  this.fullDeactivate();
};

Window_MessageBacklog.prototype.fullDeactivate = function() {
  this.updateInputData();
  Input.clear();
  TouchInput.clear();
  this.deactivate();
  this.openness = 0;
  this.deselect();
  if (this._returnWindow) {
    this._returnWindow.activate();
    this._returnWindow = undefined;
  }
  if (this._backgroundPicture) this.setBgPictureOpacity(0)
};

Window_MessageBacklog.prototype.isCursorVisible = function() {
  return false;
};

Window_MessageBacklog.prototype.cursorDown = function(wrap) {
  var index = this.bottomRow();
  var maxItems = this.maxItems();
  var maxCols = this.maxCols();
  wrap = Yanfly.Param.MsgBacklogScrollWrap;
  if (index < maxItems - maxCols || (wrap && maxCols === 1)) {
    this.moveSelect((index + maxCols) % maxItems);
  }
};

Window_MessageBacklog.prototype.cursorUp = function(wrap) {
  var index = this.topRow();
  var maxItems = this.maxItems();
  var maxCols = this.maxCols();
  wrap = Yanfly.Param.MsgBacklogScrollWrap;
  if (index >= maxCols || (wrap && maxCols === 1)) {
    this.moveSelect((index - maxCols + maxItems) % maxItems);
  }
};

Window_MessageBacklog.prototype.cursorPagedown = function() {
  var index = this.index();
  var maxItems = this.maxItems();
  if (this.topRow() + this.maxPageRows() < this.maxRows()) {
    SoundManager.playCursor();
  }
  Window_Selectable.prototype.cursorPagedown.call(this);
  if (this._scrollSprite) this._scrollSprite.updatePosition();
};

Window_MessageBacklog.prototype.cursorPageup = function() {
  var index = this.index();
  if (this.topRow() > 0) {
    SoundManager.playCursor();
  }
  Window_Selectable.prototype.cursorPageup.call(this);
  if (this._scrollSprite) this._scrollSprite.updatePosition();
};

Window_MessageBacklog.prototype.processTouch = function() {
  if (!this.isOpenAndActive()) return;
  this._touchHold -= 1;
  if (TouchInput.isPressed() && this._touchHold <= 0) {
    if (TouchInput.y < Graphics.boxHeight / 4) {
      this.scrollUp();
      this._touchHold = Yanfly.Param.MsgBacklogScrollSpd;
    } else if (TouchInput.y > Graphics.boxHeight * 3 / 4) {
      this.scrollDown();
      this._touchHold = Yanfly.Param.MsgBacklogScrollSpd;
    } else {
      this.processOk();
    }
  } else if (TouchInput.isCancelled()) {
    if (this.isCancelEnabled()) {
      this.processCancel();
    }
  }
};

Window_MessageBacklog.prototype.drawItem = function(index) {
  var rect = this.itemRectForText(index);
  var align = this.itemTextAlign();
  var symbol = this.commandSymbol(index);
  if (symbol === 'linebreak') {
    this.drawHorzLine(rect.y);
    this.resetFontSettings();
  } else if (symbol === 'text') {
    this.drawTextEx(this.commandName(index), rect.x, rect.y);
  } else if (symbol === 'buffer') {
    if (index !== this.topRow()) return;
    var ext = this._list[index].ext;
    this.drawItem(index - ext);
  }
};

Window_MessageBacklog.prototype.drawHorzLine = function(y) {
  var lineY = y + this.lineHeight() / 2 - 1;
  this.contents.paintOpacity = 48;
  this.contents.fillRect(0, lineY, this.contentsWidth(), 2, this.normalColor());
  this.contents.paintOpacity = 255;
};

Window_MessageBacklog.prototype.drawTextEx = function(text, x, y) {
  if (text) {
    var textState = { index: 0, x: x, y: y, left: x };
    textState.text = this.convertEscapeCharacters(text);
    textState.height = this.calcTextHeight(textState, false);
    while (textState.index < textState.text.length) {
      this.processCharacter(textState);
    }
    return textState.x - x;
  } else {
    return 0;
  }
};

Window_MessageBacklog.prototype.textHeightEx = function(text) {
  return this.getTextExHeight(text, 0, 0);
};

Window_MessageBacklog.prototype.getTextExHeight = function(text, x, y) {
  if (text) {
    var textState = { index: 0, x: x, y: y, left: x };
    textState.text = this.convertEscapeCharacters(text);
    textState.height = this.calcTextHeight(textState, false);
    while (textState.index < textState.text.length) {
      this.processCharacter(textState);
    }
    this.contents.clear();
    return textState.y;
  } else {
    return 0;
  }
};

Window_MessageBacklog.prototype.makeCommandList = function() {
  if (!this._ready) return;
  var backlog = $gameSystem.getMessageBacklog();
  var length = backlog.length;
  for (var i = 0; i < length; ++i) {
    var text = backlog[i];
    this.addCommand('---', 'linebreak');
    this.addIndividualLines(text);
  }
  this.addCommand('---', 'linebreak');
};

Window_MessageBacklog.prototype.addIndividualLines = function(text) {
  var text = this.convertMessageText(text);
  var items = text.split('\n');
  var length = items.length;
  for (var i = 0; i < length; ++i) {
    var line = items[i];
    if (line.length <= 0) continue;
    this.addCommand(line, 'text');
    this.addWordWrapBuffer(line);
  }
};

Window_MessageBacklog.prototype.convertMessageText = function(text) {
  text = this.convertMessageMacros(text);
  text = text.replace(/\\/g, '\x1b');
  text = this.convertNameboxCodes(text);
  text = this.convertBasicCodes(text);
  text = this.convertSpecialCodes(text);
  text = this.removeMessageBoxOnlyCodes(text);
  return text;
};

Window_MessageBacklog.prototype.convertMessageMacros = function(text) {
  if (Imported.YEP_X_MessageMacros1) {
    text = this.convertMacroText(text);
  }
  return text;
};

Window_MessageBacklog.prototype.convertNameboxCodes = function(text) {
  var name = '';
  // \x1b
  if (text.match(/\x1bN\<(.*?)\>/gi)) {
    name = RegExp.$1;
  } else if (text.match(/\x1bN(\d+)\<(.*?)\>/gi)) {
    name = RegExp.$2;
  } else if (text.match(/\x1bN(?:T|D|L|C|R|DL|DC|DR|TL|TC|TR)\<(.*?)\>/gi)) {
    name = RegExp.$1;
  } else if
  (text.match(/\x1bN(?:T|D|L|C|R|DL|DC|DR|TL|TC|TR)(\d+)\<(.*?)\>/gi)) {
    name = RegExp.$2;
  }
  if (name.length > 0) {
    var nameText = Yanfly.Param.MSGNameBoxText + name + '\\c[0]\n';
    text = nameText + text;
  }
  // \x1b version
  text = text.replace(/\x1bN\<(.*?)\>/gi, '');
  text = text.replace(/\x1bN(\d+)\<(.*?)\>/gi, '');
  text = text.replace(/\x1bN(?:T|D|L|C|R|DL|DC|DR|TL|TC|TR)\<(.*?)\>/gi, '');
  text = text.replace(/\x1bN\<(.*?)\>/gi, '');
  text =
    text.replace(/\x1bN(?:T|D|L|C|R|DL|DC|DR|TL|TC|TR)(\d+)\<(.*?)\>/gi, '');
  return text;
};

Window_MessageBacklog.prototype.convertBasicCodes = function(text) {
  text = text.replace(/\\/g, '\x1b');
  text = text.replace(/\x1b\x1b/g, '\\');
  text = text.replace(/\x1bV\[(\d+)\]/gi, function() {
    return $gameVariables.value(parseInt(arguments[1]));
  }.bind(this));
  text = text.replace(/\x1bV\[(\d+)\]/gi, function() {
    return $gameVariables.value(parseInt(arguments[1]));
  }.bind(this));
  text = text.replace(/\x1bN\[(\d+)\]/gi, function() {
    return this.actorName(parseInt(arguments[1]));
  }.bind(this));
  text = text.replace(/\x1bP\[(\d+)\]/gi, function() {
    return this.partyMemberName(parseInt(arguments[1]));
  }.bind(this));
  text = text.replace(/\x1bG/gi, TextManager.currencyUnit);
  return text;
};

Window_MessageBacklog.prototype.convertSpecialCodes = function(text) {
  if (Imported.YEP_X_ExtMesPack2) {
    text = this.convertItemQuantitiesCodes(text);
    text = this.convertActorParameterCodes(text);
    text = this.convertEnemyParameterCodes(text);
  }
  return text;
};

Window_MessageBacklog.prototype.removeMessageBoxOnlyCodes = function(text) {
  text = text.replace(/\x1b/gi, '\\');
  // Message Core
  text = text.replace(/\\AF\[(\d+)\]/gi, '');
  text = text.replace(/\\PF\[(\d+)\]/gi, '');
  text = text.replace(/\\FS\[(\d+)\]/gi, '');
  // Extended Message Pack 1
  text = text.replace(/\\LSON/gi, '');
  text = text.replace(/\\LSOFF/gi, '');
  text = text.replace(/\\LSRESET/gi, '');
  text = text.replace(/\\LSR/gi, '');
  text = text.replace(/\\LSN\[(.*?)\]/gi, '');
  text = text.replace(/\\LSV\[(\d+)\]/gi, '');
  text = text.replace(/\\LSPIV\[(\d+)\]/gi, '');
  text = text.replace(/\\LSPI\[(\d+)\]/gi, '');
  text = text.replace(/\\LSPAV\[(\d+)\]/gi, '');
  text = text.replace(/\\LSPA\[(\d+)\]/gi, '');
  text = text.replace(/\\LSI\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGPOSX\[(.*?)\]/gi, '');
  text = text.replace(/\\MSGPOSY\[(.*?)\]/gi, '');
  text = text.replace(/\\MSGEVENT\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGACTOR\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGPARTY\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGENEMY\[(\d+)\]/gi, '');
  text = text.replace(/\\AUTOEVENT\[(\d+)\]/gi, '');
  text = text.replace(/\\AUTOACTOR\[(\d+)\]/gi, '');
  text = text.replace(/\\AUTOPARTY\[(\d+)\]/gi, '');
  text = text.replace(/\\AUTOENEMY\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGROWS\[(.*?)\]/gi, '');
  text = text.replace(/\\MSGWIDTH\[(.*?)\]/gi, '');
  text = text.replace(/\\AUTO/gi, '');
  text = text.replace(/\\MSGRESET/gi, '');
  text = text.replace(/\\FACEINDEX\[(\d+)\]/gi, '');
  return text;
};

Window_MessageBacklog.prototype.addWordWrapBuffer = function(text) {
  if (!text.match(/<(?:WordWrap)>/gi)) return;
  var textHeight = this.textHeightEx(text);
  var bufferTimes = Math.ceil(textHeight / this.lineHeight());
  for (var i = 1; i <= bufferTimes; ++i) {
    this.addCommand('', 'buffer', true, i);
  }
};

//=============================================================================
// Utilities
//=============================================================================

Yanfly.Util = Yanfly.Util || {};

if (!Yanfly.Util.toGroup) {

Yanfly.Util.toGroup = function(inVal) {
  return inVal;
}

};

//=============================================================================
// End of File
//=============================================================================
} else {

var text = '';
text += 'You are getting this error because you are trying to run ';
text += 'YEP_X_MessageBacklog without the required plugins. Please visit ';
text += 'Yanfly.moe and install the required plugins neede for this plugin ';
text += 'found in this plugin\'s help file before you can use it.';
console.log(text);
require('nw.gui').Window.get().showDevTools();

}; // Imported.YEP_MessageCore


code:
//=============================================================================
// Yanfly Engine Plugins - Battle Engine Extension - Visual HP Gauge
// YEP_X_VisualHpGauge.js
// Translate to Japanese : munokura.tk
//=============================================================================

var Imported = Imported || {};
Imported.YEP_X_VisualHpGauge = true;

var Yanfly = Yanfly || {};
Yanfly.VHG = Yanfly.VHG || {};
Yanfly.VHG.version = 1.07

//=============================================================================
 /*:
 * @plugindesc v1.07 (Requires YEP_BattleEngineCore.js) Reveal HP Gauges
 * when a battler is selected or takes damage in battle.
 * @author Yanfly Engine Plugins
 *
 * @param ---General---
 * @default
 *
 * @param Display Actor
 * @parent ---General---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Do you wish to display the HP Gauge for actors?
 * NO - false     YES - true
 * @default true
 *
 * @param Defeat First
 * @parent ---General---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Enemies must be defeated first before showing the HP Gauge.
 * NO - false     YES - true
 * @default false
 *
 * @param Always Visible
 * @parent ---General---
 * @type boolean
 * @on YES
 * @off NO
 * @desc HP Gauge is always visible and doesn't fade away.
 * NO - false     YES - true
 * @default false
 *
 * @param ---Appearance---
 * @default
 *
 * @param Minimum Gauge Width
 * @parent ---Appearance---
 * @type number
 * @min 1
 * @desc This is the minimum width in pixels for HP Gauges.
 * @default 144
 *
 * @param Gauge Height
 * @parent ---Appearance---
 * @type number
 * @min 1
 * @desc This is the height in pixels for HP Gauges.
 * @default 18
 *
 * @param Back Color
 * @parent ---Appearance---
 * @desc This is the text color used for the back of HP Gauges.
 * @default 19
 *
 * @param HP Color 1
 * @parent ---Appearance---
 * @type number
 * @min 0
 * @max 31
 * @desc This is the text color used for the 1st part of HP Gauges.
 * @default 20
 *
 * @param HP Color 2
 * @parent ---Appearance---
 * @type number
 * @min 0
 * @max 31
 * @desc This is the text color used for the 2nd part of HP Gauges.
 * @default 21
 *
 * @param Gauge Duration
 * @parent ---Appearance---
 * @type number
 * @min 0
 * @desc This is the frames the HP gauge will continue to show after
 * it finishes draining or filling.
 * @default 30
 *
 * @param Gauge Position
 * @parent ---Appearance---
 * @type boolean
 * @on Above
 * @off Below
 * @desc Where do you wish to show the HP gauge?
 * BELOW - false     ABOVE - true
 * @default false
 *
 * @param Y Buffer
 * @parent ---Appearance---
 * @type number
 * @desc How much do you wish to shift the gauge Y position?
 * @default -16
 *
 * @param Use Thick Gauges
 * @parent ---Appearance---
 * @type boolean
 * @on Thick
 * @off Normal
 * @desc Use the thick gauges provided by this plugin?
 * Default - false     Thick - true
 * @default true
 *
 * @param ---Text Display---
 * @default
 *
 * @param Show HP
 * @parent ---Text Display---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Show the actual 'HP' text.
 * NO - false     YES - true
 * @default false
 *
 * @param Show Value
 * @parent ---Text Display---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Show the HP value.
 * NO - false     YES - true
 * @default false
 *
 * @param Show Max
 * @parent ---Text Display---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Show the MaxHP value if value is shown?
 * NO - false     YES - true
 * @default false
 *
 * @help
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * This plugin requires YEP_BattleEngineCore.
 * Make sure this plugin is located under YEP_BattleEngineCore in the plugin
 * list.
 *
 * This plugin shows the HP Gauges of enemies as they're selected or while they
 * take damage. You can also opt for actors to show their HP Gauge as well.
 * Adjust the parameters to change the way you want the HP Gauges to appear.
 *
 * By default, enemies would need to be defeated first in order for the gauges
 * to show up. This can be changed within the parameter settings. However,
 * during battle test, the HP gauges are always shown unless the enemy has a
 * hidden HP gauge.
 *
 * ============================================================================
 * Notetags
 * ============================================================================
 *
 * Class and Enemy Notetags:
 *   <Hide HP Gauge>
 *   This HP gauge will always be hidden if this notetag is present.
 *
 *   <Show HP Gauge>
 *   This HP gauge will always be shown if this notetag is present while the
 *   target is selected or taking damage.
 *
 *   <HP Gauge Width: x>
 *   This will set the battler's HP Gauge width to x pixels. However, if this
 *   width is less than the minimum width, minimum width will take priority.
 *
 *   <HP Gauge Height: x>
 *   This set's the HP Gauge height to x pixels.
 *
 *   <HP Gauge Back Color: x>
 *   This changes the HP Gauge's back color to x text color.
 *
 *   <HP Gauge Color 1: x>
 *   This changes the HP Gauge's color 1 to x text color.
 *
 *   <HP Gauge Color 2: x>
 *   This changes the HP Gauge's color 2 to x text color.
 *
 * ============================================================================
 * Changelog
 * ============================================================================
 *
 * Version 1.07:
 * - Updated for RPG Maker MV version 1.5.0.
 *
 * Version 1.06:
 * - Compatibility update with State Categories.
 *
 * Version 1.05:
 * - Updated for RPG Maker MV version 1.1.0.
 *
 * Version 1.04:
 * - Optimization update.
 *
 * Version 1.03:
 * - Fixed a bug when Escape skill-effects are used on battlers.
 *
 * Version 1.02:
 * - Fixed a bug with gauge height not adjusting.
 *
 * Version 1.01b:
 * - Fixed a bug regarding dependancy checks.
 * - Fixed many bugs regarding stacking errors.
 *
 * Version 1.01:
 * - Rewrote the good majority of plugin to accomodate the following features:
 * ---'Always Visible' parameter.
 * ---'Gauge Position' parameter.
 * ---'Y Buffer' parameter.
 * ---'Use Thick Gauges' parameter.
 * ---'Show HP' parameter.
 * ---'Show Value' parameter.
 * ---'Show Max' parameter.
 *
 * Version 1.00:
 * - Finished Plugin!
 */
 /*:ja
 * @plugindesc v1.07 (要YEP_BattleEngineCore.js) バトラーが選択されたとき、または戦闘でダメージを受けたときにHPゲージを表示します。
 * @author Yanfly Engine Plugins
 *
 * @param ---一般---
 * @default
 *
 * @param Display Actor
 * @parent ---一般---
 * @type boolean
 * @on YES
 * @off NO
 * @desc アクターのHPゲージを表示しますか？
 * NO - false     YES - true
 * @default true
 *
 * @param Defeat First
 * @parent ---一般---
 * @type boolean
 * @on YES
 * @off NO
 * @desc 倒したことがある敵のみのHPゲージを表示しますか？
 * NO - false     YES - true
 * @default false
 *
 * @param Always Visible
 * @parent ---一般---
 * @type boolean
 * @on YES
 * @off NO
 * @desc HPゲージを常に表示しますか？
 * NO - false     YES - true
 * @default false
 *
 * @param ---外観---
 * @default
 *
 * @param Minimum Gauge Width
 * @parent ---外観---
 * @type number
 * @min 1
 * @desc HPゲージの最小幅（ピクセル単位）
 * @default 144
 *
 * @param Gauge Height
 * @parent ---外観---
 * @type number
 * @min 1
 * @desc HPゲージの高さ（ピクセル単位）
 * @default 18
 *
 * @param Back Color
 * @parent ---外観---
 * @desc HPゲージの裏面に使用される文字色
 * @default 19
 *
 * @param HP Color 1
 * @parent ---外観---
 * @type number
 * @min 0
 * @max 31
 * @desc HPゲージの最初の部分に使用される文字色
 * @default 20
 *
 * @param HP Color 2
 * @parent ---外観---
 * @type number
 * @min 0
 * @max 31
 * @desc HPゲージの第2部に使用される文字色
 * @default 21
 *
 * @param Gauge Duration
 * @parent ---外観---
 * @type number
 * @min 0
 * @desc ダメージを受けた(または回復)後にHPゲージを表示し続けるフレーム数
 * @default 30
 *
 * @param Gauge Position
 * @parent ---外観---
 * @type boolean
 * @on 上方
 * @off 下方
 * @desc HPゲージを表示する場所
 * 下方 - false     上方 - true
 * @default false
 *
 * @param Y Buffer
 * @parent ---外観---
 * @type number
 * @desc ゲージのY位置のシフト
 * @default -16
 *
 * @param Use Thick Gauges
 * @parent ---外観---
 * @type boolean
 * @on YES
 * @off NO
 * @desc このプラグインが提供する厚いゲージを使いますか？
 * NO - false     YES - true
 * @default true
 *
 * @param ---テキスト表示---
 * @default
 *
 * @param Show HP
 * @parent ---テキスト表示---
 * @type boolean
 * @on YES
 * @off NO
 * @desc 「HP」というテキストを表示しますか？
 * NO - false     YES - true
 * @default false
 *
 * @param Show Value
 * @parent ---テキスト表示---
 * @type boolean
 * @on YES
 * @off NO
 * @desc 現在のHP値を表示しますか？
 * NO - false     YES - true
 * @default false
 *
 * @param Show Max
 * @parent ---テキスト表示---
 * @type boolean
 * @on YES
 * @off NO
 * @desc 現在のHP値値が表示されている場合、最大HP値を表示しますか？
 * NO - false     YES - true
 * @default false
 *
 * @help
 * 翻訳:ムノクラ
 * https://munokura.tk/
 * https://twitter.com/munokura/
 *
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * このプラグインはYEP_BattleEngineCoreを必要とします。
 * プラグインリスト中のYEP_BattleEngineCoreの下にあることを確認してください。
 *
 * このプラグインは、敵が選択されたとき、またはダメージを受けたときに
 * 敵のHPゲージを表示します。
 * アクターが自分のHPゲージを表示するように選択することもできます。
 * HPゲージの表示方法を変更するには、パラメータを調整します。
 *
 * デフォルトでは、ゲージが表示されるようにするには、
 * まず敵を倒す必要があります。
 * これはパラメータ設定内で変更できます。
 * ただし、戦闘テスト中は、敵に隠されたHPゲージがない限り、
 * HPゲージは常に表示されます。
 *
 * ============================================================================
 * Notetags
 * ============================================================================
 *
 * クラスと敵のメモタグ:
 *   <Hide HP Gauge>
 *   このタグが存在する場合、このHPゲージは常に非表示になります。
 *
 *   <Show HP Gauge>
 *   このタグが存在する場合、このHPゲージはターゲットが選択されているか
 *   ダメージを受けている間に常に表示されます。
 *
 *   <HP Gauge Width: x>
 *   バトラーのHPゲージ幅をxピクセルに設定します。
 *   ただし、この幅が最小幅より小さい場合は、最小幅が優先されます。
 *
 *   <HP Gauge Height: x>
 *   HPゲージの高さをxピクセルに設定します。
 *
 *   <HP Gauge Back Color: x>
 *   HPゲージの背景色が x 文字色に変わります。
 *
 *   <HP Gauge Color 1: x>
 *   HPゲージの色1が x の文字色に変わります。
 *
 *   <HP Gauge Color 2: x>
 *   HPゲージの色2が x 文字色に変わります。
 *
 * ============================================================================
 * Changelog
 * ============================================================================
 *
 * Version 1.07:
 * - Updated for RPG Maker MV version 1.5.0.
 *
 * Version 1.06:
 * - Compatibility update with State Categories.
 *
 * Version 1.05:
 * - Updated for RPG Maker MV version 1.1.0.
 *
 * Version 1.04:
 * - Optimization update.
 *
 * Version 1.03:
 * - Fixed a bug when Escape skill-effects are used on battlers.
 *
 * Version 1.02:
 * - Fixed a bug with gauge height not adjusting.
 *
 * Version 1.01b:
 * - Fixed a bug regarding dependancy checks.
 * - Fixed many bugs regarding stacking errors.
 *
 * Version 1.01:
 * - Rewrote the good majority of plugin to accomodate the following features:
 * ---'Always Visible' parameter.
 * ---'Gauge Position' parameter.
 * ---'Y Buffer' parameter.
 * ---'Use Thick Gauges' parameter.
 * ---'Show HP' parameter.
 * ---'Show Value' parameter.
 * ---'Show Max' parameter.
 *
 * Version 1.00:
 * - Finished Plugin!
 */
//=============================================================================

if (Imported.YEP_BattleEngineCore) {

//=============================================================================
// Parameter Variables
//=============================================================================

Yanfly.Parameters = PluginManager.parameters('YEP_X_VisualHpGauge');
Yanfly.Param = Yanfly.Param || {};

Yanfly.Param.VHGDisplayActor = String(Yanfly.Parameters['Display Actor']);
Yanfly.Param.VHGDefeatFirst = String(Yanfly.Parameters['Defeat First']);
Yanfly.Param.VHGAlwaysShow = eval(String(Yanfly.Parameters['Always Visible']));

Yanfly.Param.VHGMinHpWidth = Number(Yanfly.Parameters['Minimum Gauge Width']);
Yanfly.Param.VHGGaugeHeight = Number(Yanfly.Parameters['Gauge Height']);
Yanfly.Param.VHGBackColor = Number(Yanfly.Parameters['Back Color']);
Yanfly.Param.VHGHpColor1 = Number(Yanfly.Parameters['HP Color 1']);
Yanfly.Param.VHGHpColor2 = Number(Yanfly.Parameters['HP Color 2']);
Yanfly.Param.VHGGaugeDuration = Number(Yanfly.Parameters['Gauge Duration']);
Yanfly.Param.VHGGaugePos = eval(String(Yanfly.Parameters['Gauge Position']));
Yanfly.Param.VHGBufferY = Number(Yanfly.Parameters['Y Buffer']);
Yanfly.Param.VHGThick = eval(String(Yanfly.Parameters['Use Thick Gauges']));

Yanfly.Param.VHGShowHP = eval(String(Yanfly.Parameters['Show HP']));
Yanfly.Param.VHGShowValue = eval(String(Yanfly.Parameters['Show Value']));
Yanfly.Param.VHGShowMax = eval(String(Yanfly.Parameters['Show Max']));

//=============================================================================
// DataManager
//=============================================================================

Yanfly.VHG.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded;
DataManager.isDatabaseLoaded = function() {
  if (!Yanfly.VHG.DataManager_isDatabaseLoaded.call(this)) return false;
  if (!Yanfly._loaded_YEP_X_VisualHpGauge) {
  	this.processVHGNotetags($dataClasses);
  	this.processVHGNotetags($dataEnemies);
    Yanfly._loaded_YEP_X_VisualHpGauge = true;
  }
	return true;
};

DataManager.processVHGNotetags = function(group) {
	for (var n = 1; n < group.length; n++) {
		var obj = group[n];
		var notedata = obj.note.split(/[\r\n]+/);

    obj.hideHpGauge = false;
		obj.showHpGauge = false;
		obj.hpGaugeWidth = 0;
		obj.hpGaugeHeight = Yanfly.Param.VHGGaugeHeight;
		obj.hpGaugeBackColor = Yanfly.Param.VHGBackColor;
		obj.hpGaugeColor1 = Yanfly.Param.VHGHpColor1;
		obj.hpGaugeColor2 = Yanfly.Param.VHGHpColor2;

		for (var i = 0; i < notedata.length; i++) {
			var line = notedata[i];
			if (line.match(/<(?:HIDE HP GAUGE)>/i)) {
				obj.hideHpGauge = true;
			} else if (line.match(/<(?:SHOW HP GAUGE)>/i)) {
				obj.showHpGauge = true;
			} else if (line.match(/<(?:HP GAUGE WIDTH):[ ](\d+)>/i)) {
				obj.hpGaugeWidth = parseInt(RegExp.$1);
			} else if (line.match(/<(?:HP GAUGE HEIGHT):[ ](\d+)>/i)) {
				obj.hpGaugeHeight = parseInt(RegExp.$1);
			} else if (line.match(/<(?:HP GAUGE BACK COLOR):[ ](\d+)>/i)) {
				obj.hpGaugeBackColor = parseInt(RegExp.$1);
			} else if (line.match(/<(?:HP GAUGE COLOR 1):[ ](\d+)>/i)) {
				obj.hpGaugeColor1 = parseInt(RegExp.$1);
			} else if (line.match(/<(?:HP GAUGE COLOR 2):[ ](\d+)>/i)) {
				obj.hpGaugeColor2 = parseInt(RegExp.$1);
			}
		}
	}
};

//=============================================================================
// Game_System
//=============================================================================

Yanfly.VHG.Game_System_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
    Yanfly.VHG.Game_System_initialize.call(this);
		this.initShownHpGauge();
};

Game_System.prototype.initShownHpGauge = function() {
    this._shownHpGauge = [];
};

Game_System.prototype.showHpGaugeEnemy = function(id) {
    if (this._shownHpGauge === undefined) this.initShownHpGauge();
		if (!eval(Yanfly.Param.VHGDefeatFirst)) return true;
		return this._shownHpGauge.contains(id);
};

Game_System.prototype.addHpGaugeEnemy = function(id) {
    if (this._shownHpGauge === undefined) this.initShownHpGauge();
		if (this._shownHpGauge.contains(id)) return;
		this._shownHpGauge.push(id);
};

//=============================================================================
// Game_BattlerBase
//=============================================================================

Yanfly.VHG.Game_BattlerBase_die = Game_BattlerBase.prototype.die;
Game_BattlerBase.prototype.die = function() {
  Yanfly.VHG.Game_BattlerBase_die.call(this);
  if (!this.isEnemy()) return;
  if (eval(Yanfly.Param.VHGDefeatFirst)) {
    if (!$gameSystem.showHpGaugeEnemy(this._enemyId)) this._noHpGauge = true;
  }
  $gameSystem.addHpGaugeEnemy(this._enemyId);
};

//=============================================================================
// Game_Battler
//=============================================================================

Game_Battler.prototype.hpGaugeVisible = function() {
		if (this._noHpGauge) return false;
    if (this.isHidden()) return false;
		return true;
};

Game_Battler.prototype.hpGaugeWidth = function() {
		var width = Math.max(this.spriteWidth(),	Yanfly.Param.VHGMinHpWidth);
		return (width & 1) ? width + 1 : width;
};

Game_Battler.prototype.hpGaugeHeight = function() {
		return Yanfly.Param.VHGGaugeHeight;
};

Game_Battler.prototype.hpGaugeBackColor = function() {
		return Yanfly.Param.VHGBackColor;
};

Game_Battler.prototype.hpGaugeColor1 = function() {
		return Yanfly.Param.VHGHpColor1;
};

Game_Battler.prototype.hpGaugeColor2 = function() {
		return Yanfly.Param.VHGHpColor2;
};

//=============================================================================
// Game_Actor
//=============================================================================

Game_Actor.prototype.hpGaugeVisible = function() {
    if (this.isHidden()) return false;
		if (this.currentClass().showHpGauge) return true;
		if (!eval(Yanfly.Param.VHGDisplayActor)) return false;
		if (this.currentClass().hideHpGauge) return false;
		return Game_Battler.prototype.hpGaugeVisible.call(this);
};

Game_Actor.prototype.hpGaugeWidth = function() {
		if (this.currentClass().hpGaugeWidth > 0) {
			var width = this.currentClass().hpGaugeWidth;
		} else {
			var width = this.spriteWidth();
		}
		width = Math.max(width,	Yanfly.Param.VHGMinHpWidth);
		return (width & 1) ? width + 1 : width;
};

Game_Actor.prototype.hpGaugeHeight = function() {
		return this.currentClass().hpGaugeHeight;
};

Game_Actor.prototype.hpGaugeBackColor = function() {
		return this.currentClass().hpGaugeBackColor;
};

Game_Actor.prototype.hpGaugeColor1 = function() {
		return this.currentClass().hpGaugeColor1;
};

Game_Actor.prototype.hpGaugeColor2 = function() {
		return this.currentClass().hpGaugeColor2;
};

//=============================================================================
// Game_Enemy
//=============================================================================

Game_Enemy.prototype.hpGaugeVisible = function() {
    if (this.isHidden()) return false;
		if (this.enemy().hideHpGauge) return false;
    if (BattleManager.isBattleTest()) return true;
		if (this.enemy().showHpGauge) return true;
		if (!$gameSystem.showHpGaugeEnemy(this._enemyId)) return false;
		return Game_Battler.prototype.hpGaugeVisible.call(this);
};

Yanfly.VHG.Game_Enemy_revive = Game_Enemy.prototype.revive;
Game_Enemy.prototype.revive = function() {
    if (this._hp === 0) this._noHpGauge = false;
		Yanfly.VHG.Game_Enemy_revive.call(this);
};

Game_Enemy.prototype.hpGaugeWidth = function() {
		if (this.enemy().hpGaugeWidth > 0) {
			var width = this.enemy().hpGaugeWidth;
		} else {
			var width = this.spriteWidth();
		}
		width = Math.max(width,	Yanfly.Param.VHGMinHpWidth);
		return (width & 1) ? width + 1 : width;
};

Game_Enemy.prototype.hpGaugeHeight = function() {
		return this.enemy().hpGaugeHeight;
};

Game_Enemy.prototype.hpGaugeBackColor = function() {
		return this.enemy().hpGaugeBackColor;
};

Game_Enemy.prototype.hpGaugeColor1 = function() {
		return this.enemy().hpGaugeColor1;
};

Game_Enemy.prototype.hpGaugeColor2 = function() {
		return this.enemy().hpGaugeColor2;
};

//=============================================================================
// Sprite_Battler
//=============================================================================

Yanfly.VHG.Sprite_Battler_update = Sprite_Battler.prototype.update;
Sprite_Battler.prototype.update = function() {
    Yanfly.VHG.Sprite_Battler_update.call(this);
    this.createVisualHpGaugeWindow();
};

Sprite_Battler.prototype.createVisualHpGaugeWindow = function() {
		if (this._createdVisualHpGaugeWindow) return;
		if (!this._battler) return;
		if (this.checkVisualATBGauge()) {
			if (!this._visualATBWindow) return;
			if (!this.parent.parent.children.contains(this._visualATBWindow)) return;
		}
		this._createdVisualHpGaugeWindow = true;
    this._visualHpGauge = new Window_VisualHPGauge();
    this._visualHpGauge.setBattler(this._battler);
    this.parent.parent.addChild(this._visualHpGauge);
};

Sprite_Battler.prototype.checkVisualATBGauge = function() {
    if (!Imported.YEP_X_BattleSysATB) return false;
    if (!BattleManager.isATB()) return false;
    if (!Imported.YEP_X_VisualATBGauge) return false;
    return this._battler.isEnemy();
};

Yanfly.VHG.Sprite_Battler_setBattler = Sprite_Battler.prototype.setBattler;
Sprite_Battler.prototype.setBattler = function(battler) {
    Yanfly.VHG.Sprite_Battler_setBattler.call(this, battler);
    if (this._visualHpGauge) this._visualHpGauge.setBattler(battler);
};

//=============================================================================
// Window_VisualHPGauge
//=============================================================================

function Window_VisualHPGauge() {
    this.initialize.apply(this, arguments);
}

Window_VisualHPGauge.prototype = Object.create(Window_Base.prototype);
Window_VisualHPGauge.prototype.constructor = Window_VisualHPGauge;

Window_VisualHPGauge.prototype.initialize = function() {
    this._opacitySpeed = 255 / Yanfly.Param.VHGGaugeDuration;
    this._dropSpeed = 0;
    this._visibleCounter = 0;
    Window_Base.prototype.initialize.call(this, 0, 0, 1, 1);
    this._battler = null;
    this._requestRefresh = false;
    this._currentHpValue = 0;
    this._displayedValue = 0;
    this.contentsOpacity = 0;
    this.opacity = 0;
};

Window_VisualHPGauge.prototype.setBattler = function(battler) {
    if (this._battler === battler) return;
    this._battler = battler;
    this._currentHpValue = this._battler ? this._battler.hp : 0;
    this._displayedValue = this._battler ? this._battler.hp : 0;
};

Window_VisualHPGauge.prototype.update = function() {
    Window_Base.prototype.update.call(this);
    if (!this._battler) return;
    this.updateWindowAspects();
};

Window_VisualHPGauge.prototype.updateWindowAspects = function() {
    this.updateWindowSize();
    this.updateWindowPosition();
    this.updateOpacity();
    this.updateHpPosition();
    this.updateRefresh();
};

Window_VisualHPGauge.prototype.updateWindowSize = function() {
    var spriteWidth = this._battler.hpGaugeWidth();
    var width = spriteWidth + this.standardPadding() * 2;
    width = Math.min(width, Graphics.boxWidth + this.standardPadding() * 2);
    var height = Math.max(this.lineHeight(), this.gaugeHeight() + 4);
    height += this.standardPadding() * 2;
    if (width === this.width && height === this.height) return;
    this.width = width;
    this.height = height;
    this.createContents();
    this._requestRefresh = true;
    this.makeWindowBoundaries();
};

Window_VisualHPGauge.prototype.makeWindowBoundaries = function() {
    if (!this._requestRefresh) return;
    this._minX = -1 * this.standardPadding();
    this._maxX = Graphics.boxWidth - this.width + this.standardPadding();
    this._minY = -1 * this.standardPadding();
    this._maxY = Graphics.boxHeight - this.height + this.standardPadding();
    //this._maxY -= SceneManager._scene._statusWindow.height;
};

Window_VisualHPGauge.prototype.updateWindowPosition = function() {
    if (!this._battler) return;
    var battler = this._battler;
    this.x = battler.spritePosX();
    this.x -= Math.ceil(this.width / 2);
    this.x = this.x.clamp(this._minX, this._maxX);
    this.y = battler.spritePosY();
    if (Yanfly.Param.VHGGaugePos) {
      this.y -= battler.spriteHeight();
    } else {
      this.y -= this.standardPadding();
    }
    this.y = this.y.clamp(this._minY, this._maxY);
    this.y += Yanfly.Param.VHGBufferY;
};

Window_VisualHPGauge.prototype.updateOpacity = function() {
    if (this.isShowWindow()) {
      this.contentsOpacity += 32;
    } else {
      this.contentsOpacity -= 32;
    }
};

Window_VisualHPGauge.prototype.isShowWindow = function() {
    if (!this._battler.isAppeared()) return false;
    if (!this._battler.hpGaugeVisible()) return false;
    if (Yanfly.Param.VHGAlwaysShow && !this._battler.isDead()) return true;
    if (this._currentHpValue !== this._displayedValue) return true;
    if (this._battler.isSelected()) return true;
    --this._visibleCounter;
    return this._visibleCounter > 0;
};

Window_VisualHPGauge.prototype.updateHpPosition = function() {
    if (!this._battler) return;
    if (this._currentHpValue !== this._battler.hp) {
      this._visibleCounter = Yanfly.Param.VHGGaugeDuration;
      this._currentHpValue = this._battler.hp;
      var difference = Math.abs(this._displayedValue - this._battler.hp);
      this._dropSpeed = Math.ceil(difference / Yanfly.Param.VHGGaugeDuration);
    }
    this.updateDisplayCounter();
};

Window_VisualHPGauge.prototype.updateDisplayCounter = function() {
    if (this._battler._barrierAltered) {
      this._battler._barrierAltered = false;
    } else if (this._currentHpValue === this._displayedValue) {
      return;
    }
    var d = this._dropSpeed;
    var c = this._currentHpValue;
    if (this._displayedValue > this._currentHpValue) {
      this._displayedValue = Math.max(this._displayedValue - d, c);
    } else if (this._displayedValue < this._currentHpValue) {
      this._displayedValue = Math.min(this._displayedValue + d, c);
    }
    this._requestRefresh = true;
};

Window_VisualHPGauge.prototype.updateRefresh = function() {
    if (this._requestRefresh) this.refresh();
};

Window_VisualHPGauge.prototype.refresh = function() {
    this.contents.clear();
    if (!this._battler) return;
    this._requestRefresh = false;
    var wy = this.contents.height - this.lineHeight();
    var ww = this.contents.width;
    this.drawActorHp(this._battler, 0, wy, ww);
};

Window_VisualHPGauge.prototype.gaugeBackColor = function() {
    return this.textColor(this._battler.hpGaugeBackColor());
};

Window_VisualHPGauge.prototype.hpGaugeColor1 = function() {
    return this.textColor(this._battler.hpGaugeColor1());
};

Window_VisualHPGauge.prototype.hpGaugeColor2 = function() {
    return this.textColor(this._battler.hpGaugeColor2());
};

Window_VisualHPGauge.prototype.drawActorHp = function(actor, x, y, width) {
    width = width || 186;
    var color1 = this.hpGaugeColor1();
    var color2 = this.hpGaugeColor2();
    var rate = this._displayedValue / actor.mhp;
    if (Imported.YEP_AbsorptionBarrier && actor.barrierPoints() > 0) {
      ww = this.drawBarrierGauge(actor, x, y, width);
    } else {
      this.drawGauge(x, y, width, rate, color1, color2);
    }
    if (Yanfly.Param.VHGShowHP) {
      this.changeTextColor(this.systemColor());
      this.drawText(TextManager.hpA, x, y, 44);
    }
    if (Yanfly.Param.VHGShowValue) {
      var val = this._displayedValue
      var max = actor.mhp;
      var w = width;
      var color = this.hpColor(actor);
      this.drawCurrentAndMax(val, max, x, y, w, color, this.normalColor());
    }
};

Window_VisualHPGauge.prototype.drawCurrentAndMax = function(current, max, x, y,
                                                   width, color1, color2) {
    if (Yanfly.Param.VHGShowMax) {
      Window_Base.prototype.drawCurrentAndMax.call(this, current, max,
        x, y, width, color1, color2);
    } else {
      var align = Yanfly.Param.VHGShowHP ? 'right' : 'center';
      var text = Yanfly.Util.toGroup(current);
      this.changeTextColor(color1);
      this.drawText(text, x, y, width, align);
    }
};

Window_VisualHPGauge.prototype.gaugeHeight = function() {
    if (!this._battler) return Window_Base.prototype.gaugeHeight.call(this);
    return this._battler.hpGaugeHeight();
};

if (Imported.YEP_CoreEngine && Yanfly.Param.VHGThick) {

Window_VisualHPGauge.prototype.drawGauge =
function(dx, dy, dw, rate, color1, color2) {
    var color3 = this.gaugeBackColor();
    var fillW = Math.floor(dw * rate).clamp(0, dw);
    var gaugeH = this.gaugeHeight();
    var gaugeY = dy + this.lineHeight() - gaugeH - 2;
    if (eval(Yanfly.Param.GaugeOutline)) {
      color3.paintOpacity = this.translucentOpacity();
      this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3);
      dx += 2;
      gaugeY += 2;
      fillW = Math.max(0, fillW - 4);
      gaugeH -= 4;
    } else {
      var fillW = Math.floor(dw * rate);
      var gaugeY = dy + this.lineHeight() - gaugeH - 2;
      this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3);
    }
    this.contents.gradientFillRect(dx, gaugeY, fillW, gaugeH, color1, color2);
};

} // Imported.YEP_CoreEngine

//=============================================================================
// Utilities
//=============================================================================

Yanfly.Util = Yanfly.Util || {};

if (!Yanfly.Util.toGroup) {
    Yanfly.Util.toGroup = function(inVal) {
        return inVal;
    }
};

//=============================================================================
// End of File
//=============================================================================
};

repo_name: onms/sister

license: unknown


code:
// Copyright (c) 2016-2018 fuku
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//

// 最新版は↓から
// http://www5f.biglobe.ne.jp/~fuku-labo/library/etc/

/*:
 * @plugindesc ピクチャのちらつき防止 v1.01
 * @author fuku
 *
 * @param ピクチャの同期
 * @desc ピクチャの表示命令で読み込み完了までウェイトするかのデフォルトを設定します。
 * @default false
 *
 * @help ピクチャの表示時に、画像の読み込みが完了するまで直前の表示状態を維持します。
 * 適用すると、既に表示しているピクチャ番号のピクチャの表示内容を変更した時、
 * ロード完了まで画像が消えてしまう問題を回避できるようになります。
 *
 * 注意：「ピクチャの同期」設定は
 *   イベントコマンド「ピクチャの表示」の動作にのみ適用されます。
 *   それ以外の方法でピクチャを操作した場合には影響しません。
 *   また、ロード完了まで直前の画像を維持する機能はこの設定に関わらず動作します。
 *
 * このプラグインはリストの一番下に配置するようにしてください。
 *
 * プラグインコマンド：
 * FPAF_SET_SYNC ピクチャの同期を再設定します。
 *           パラメータにtrueを指定すると同期、falseを指定すると非同期になります。
 */

var Fuku_Plugins=Fuku_Plugins||{};
Fuku_Plugins.PictureAntiFlicker={Version:101};

(function(){
'use strict';
var plugin_name='fuku_PictureAntiFlicker';
Fuku_Plugins.PictureAntiFlicker.picture_sync=(PluginManager.parameters(plugin_name)['ピクチャの同期']==='true');

var fuku_Sprite_bitmap_setter=Object.getOwnPropertyDescriptor(Sprite.prototype,'bitmap').set;
var update_waitbitmap=function(){//Sprite_Picture
	if(this._fuku_waitbitmap.isReady()){
		fuku_Sprite_bitmap_setter.call(this,this._fuku_waitbitmap);
		this._fuku_waitbitmap=null;
	}
};

Object.defineProperty(Sprite_Picture.prototype, 'bitmap', {
	get: function() {
		return this._bitmap;
	},
	set: function(value) {
		this._fuku_waitbitmap=value;
		if(value)update_waitbitmap.call(this);
		else fuku_Sprite_bitmap_setter.call(this,null);
	},
	configurable: true
});

var sp_update=Sprite_Picture.prototype.update;
Sprite_Picture.prototype.update=function(){
	var picture=this.picture();
	var name=(picture?picture.name():'');
	if(name!==this._pictureName)this.updateBitmap();

	if(this._fuku_waitbitmap)update_waitbitmap.call(this);

	if(!this._fuku_waitbitmap){
		sp_update.call(this);
	}
};

var gi_command231=Game_Interpreter.prototype.command231;
Game_Interpreter.prototype.command231=function(){
	if(!gi_command231.call(this)){
		return false;
	}
	if(Fuku_Plugins.PictureAntiFlicker.picture_sync){
		this.setWaitMode('image');
	}
	return true;
};

var gi_pluginCommand=Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand=function(command,args){
	gi_pluginCommand.apply(this,arguments);
	switch(command){
	case 'FPAF_SET_SYNC':
		Fuku_Plugins.PictureAntiFlicker.picture_sync=(args[0]==='true');
		break;
	}
};

})();


code:
//=============================================================================
// ゲーム終了コマンド追加プラグイン
// gamEnd.js
// Copyright (c) 2018 村人Ａ
//=============================================================================

/*:ja
 * @plugindesc このプラグインはタイトル画面にウィンドウを閉じるゲーム終了コマンドを追加します。
 * @author 村人A
 *
 * @param endName
 * @desc ゲーム終了の表記です
 * @default ゲーム終了
 *
 * @help このプラグインにはプラグインコマンドはありません。
 * 「endName」にはタイトルで表記するゲーム終了のコマンド名を入れてください。
 */

(function() {

    var parameters = PluginManager.parameters('gameEnd');
    var EndName = String(parameters['endName'] || 'ゲーム終了');
	console.log(parameters['endName'])

	Window_TitleCommand.prototype.makeCommandList = function() {
		this.addCommand(TextManager.newGame,   'newGame');
		this.addCommand(TextManager.continue_, 'continue', this.isContinueEnabled());
		this.addCommand(TextManager.options,   'options');
		this.addCommand(EndName,   'gameEnd');
	};

	Scene_Title.prototype.createCommandWindow = function() {
		this._commandWindow = new Window_TitleCommand();
		this._commandWindow.setHandler('newGame',  this.commandNewGame.bind(this));
		this._commandWindow.setHandler('continue', this.commandContinue.bind(this));
		this._commandWindow.setHandler('options',  this.commandOptions.bind(this));
		this._commandWindow.setHandler('gameEnd',  this.commandGameEnd.bind(this));
		this.addWindow(this._commandWindow);
	};

	Scene_Title.prototype.commandGameEnd = function() {
		if(StorageManager.isLocalMode()){
			window.close();
		} else {
			window.open('about:blank', '_self').close();
		}
	};
})();


code:
//=============================================================================
// 滑らかカメラの移動プラグインです。
// smoothscroll.js
// Copyright (c) 2020- 村人Ａ
//=============================================================================

/*:ja
 * @plugindesc カメラの移動を滑らかにするプラグインです。
 * @author 村人A
 *
 * @help
 *
 * _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
 *
 * バージョン管理
 *
 * 20/11/11　ver1.1 キャラブレが発生する現象への対策
 * 18　ver1.0 リリース
 *
 * _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
 *
 * なめらかスクロールonの後にはカメラがプレイヤーを追う速さの数値を入れてください。
 * 1で通常のスピードです。0.02くらいがいい感じのスクロールになります。
 * イベントコマンドでスクロールをする場合は一度なめらかスクロールをoffにしてください。
 *
 * プラグインコマンド例:
 *   なめらかスライドon 0.02    # なめらかスライドon　カメラの速さを0.02に
 *   なめらかスライドoff        # なめらかスライドoff
 */

{
	'use strict';

	villaA_scrollSpeed = 0.80;
	villaA_mapscroll = false;
	villaA_smoothScrolling = false;

	//-----------------------------------------------------------------------------
	// Game_Interpreter
	//

    const _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function(command, args) {
        _Game_Interpreter_pluginCommand.call(this, command, args);
        if (command === 'なめらかスライドon') {
			villaA_smoothScrolling = true;
			villaA_scrollSpeed = args[0];
		}

        if (command === 'なめらかスライドoff') {
			villaA_smoothScrolling = false;
			villaA_scrollSpeed = 1;
		}
	}

	//-----------------------------------------------------------------------------
	// Game_Map
	//

	Game_Map.prototype.player_scrollDown = function(distance) {
		if (this.isLoopVertical()) {
			this._displayY += distance;
			this._displayY %= $dataMap.height;
			if (this._parallaxLoopY) {
				this._parallaxY += distance;
			}
		} else if (this.height() >= this.screenTileY()) {
			const lastY = this._displayY;
			const diff = this._displayY + distance*villaA_scrollSpeed;
			this._displayY = Math.min(diff, this.height() - this.screenTileY());
			this._parallaxY += this._displayY - lastY;
		}
	};

	Game_Map.prototype.player_scrollLeft = function(distance) {
		if (this.isLoopHorizontal()) {
			this._displayX += $dataMap.width - distance;
			this._displayX %= $dataMap.width;
			if (this._parallaxLoopX) {
				this._parallaxX -= distance;
			}
		} else if (this.width() >= this.screenTileX()) {
			const lastX = this._displayX;
			const diff = this._displayX - distance*villaA_scrollSpeed;
			this._displayX = Math.max(diff, 0);
			this._parallaxX += this._displayX - lastX;
		}
	};

	Game_Map.prototype.player_scrollRight = function(distance) {
		if (this.isLoopHorizontal()) {
			this._displayX += distance;
			this._displayX %= $dataMap.width;
			if (this._parallaxLoopX) {
				this._parallaxX += distance;
			}
		} else if (this.width() >= this.screenTileX()) {
			const lastX = this._displayX;
			const diff = this._displayX + distance*villaA_scrollSpeed;
			this._displayX = Math.min(diff, this.width() - this.screenTileX());
			this._parallaxX += this._displayX - lastX;
		}
	};

	Game_Map.prototype.player_scrollUp = function(distance) {
		if (this.isLoopVertical()) {
			this._displayY += $dataMap.height - distance;
			this._displayY %= $dataMap.height;
			if (this._parallaxLoopY) {
				this._parallaxY -= distance;
			}
		} else if (this.height() >= this.screenTileY()) {
			const lastY = this._displayY;
			const diff = this._displayY - distance*villaA_scrollSpeed;
			this._displayY = Math.max(diff, 0);
			this._parallaxY += this._displayY - lastY;
		}
	};

	//-----------------------------------------------------------------------------
	// Game_Player
	//

	Game_Player.prototype.updateScroll = function(lastScrolledX, lastScrolledY) {
		let villaA_roundingNum = 0
		let x1 = lastScrolledX;
		let y1 = lastScrolledY;
		const x2 = this.scrolledX();
		const y2 = this.scrolledY();

		if(villaA_smoothScrolling){
			villaA_roundingNum = 0.5;
			x1 = 8;
			y1 = 6;
		}

		if (y2-villaA_roundingNum > y1 && y2 > this.centerY()) {
			$gameMap.player_scrollDown(y2 - y1);
		}
		if (x2+villaA_roundingNum < x1 && x2 < this.centerX()) {
			$gameMap.player_scrollLeft(x1 - x2);
		}
		if (x2-villaA_roundingNum > x1 && x2 > this.centerX()) {
			$gameMap.player_scrollRight(x2 - x1);
		}
		if (y2+villaA_roundingNum < y1 && y2 < this.centerY()) {
			$gameMap.player_scrollUp(y1 - y2);
		}
	};

	//-----------------------------------------------------------------------------
	// Game_CharacterBase
	//

	Game_CharacterBase.prototype.screenX = function() {
		const tw = $gameMap.tileWidth();
		//キャラブレ対策floor
		return Math.floor(this.scrolledX() * tw + tw / 2);
	};

	Game_CharacterBase.prototype.screenY = function() {
		const th = $gameMap.tileHeight();
		//キャラブレ対策floor
		return Math.floor(this.scrolledY() * th + th - this.shiftY() - this.jumpHeight());
	};
}


code:
//ショップ画面で装備アイテムの全情報を表示
/*:

@plugindesc
ショップで装備品を購入する際、詳細な情報を
表示することができます

@author
シトラス

*/
Window_ShopStatus.prototype.pageSize = function() {
    return 1;
};
Window_ShopStatus.prototype.drawParamName = function(x, y, paramId) {
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.param(paramId), x, y, 120);
};
Window_ShopStatus.prototype.drawActorEquipInfo = function(x, y, actor) {
    var enabled = actor.canEquip(this._item);
    this.changePaintOpacity(enabled);
    this.resetTextColor();

	//アクターの名前を表示
    this.drawText(actor.name(), x, y - 30, 168);

	//ステータスの名前を表示
	for(var i = 0;i < 8;i++){
		this.drawParamName(x,132 + i*35,i);
	}

    var item1 = this.currentEquippedItem(actor, this._item.etypeId);
    if (enabled) {
        this.drawActorParamChange(x, y, actor, item1);
    }

	//現在装備しているアイテムの名前を表示
    this.drawItemName(item1, x, y + this.lineHeight() - 25);
    this.changePaintOpacity(true);
};

Window_ShopStatus.prototype.drawActorParamChange = function(x, y, actor, item1) {
    var width = this.contents.width - this.textPadding() - x;
    var changeParams = new Array(8);
	for(var i = 0;i < 8;i++){
		changeParams[i] = this._item.params[i] - (item1 ? item1.params[i] : 0);
		console.log(changeParams[i] );
		this.changeTextColor(this.paramchangeTextColor(changeParams[i] ) );
		this.drawText( (changeParams[i] > 0 ? '+' : '') + changeParams[i], x, 60 + y + i*35, width, 'right');
	}
};

path: www/js/plugins/ショップ画面で装備アイテムの全情報を表示.js


code:
//=============================================================================
// セーブ画面 / AltSaveScreen.js
//=============================================================================

/*:ja
 * v0.3.0
 * @plugindesc
 * セーブ/ロード画面のレイアウトを変更します。
 * 導入前にヘルプを読むことを推奨
 *
 * @author Declare War
 *
 * @param UseBackPicture1
 * @default true
 * @desc 背景の画像を使うかどうか(true/false)
 *
 * @param BackPicture1
 * @default Save_Back_Picture
 * @desc 背景の画像のファイル名
 *
 * @param UseBackPicture2
 * @default true
 * @desc 背景の上に表示する画像を使うかどうか(ウィンドウの代わり、true/false)
 *
 * @param BackPicture2
 * @default Save_Back_Picture2
 * @desc 背景の上に表示する画像のファイル名
 *
 * @param Opacity
 * @default 192
 * @desc ウィンドウの不透明度
 *
 * @param DrawGauge
 * @default true
 * @desc HPMPゲージを描画するかどうか(true/false)
 *
 * @param MoveLvDraw
 * @default false
 * @desc レベルの描画を名前の下にするかどうか(true/false)
 *
 * @param FontSize1
 * @default 24
 * @desc 左のウィンドウのフォントサイズ(初期設定は24)
 *
 * @param FontSize2
 * @default 28
 * @desc 右のウィンドウのフォントサイズ(初期設定は28)
 *
 * @param Color1
 * @default rgba(0,0,0,0.2)
 * @desc ファイル名表示のところの背景の色の設定1
 *
 * @param Color2
 * @default rgba(0,0,0,1)
 * @desc ファイル名表示のところの背景の色の設定2
 *
 * @param Color3
 * @default rgba(0,0,64,0.5)
 * @desc マップ名表示のところの背景の色の設定1
 *
 * @param Color4
 * @default rgba(0,0,64,0.5)
 * @desc マップ名表示のところの背景の色の設定2
 *
 * @param Color5
 * @default #00FF00
 * @desc マップ名のテキストの色
 *
 * @help このプラグインには、プラグインコマンドはありません。
 *
 * ●マップ名表示について
 * 実際のマップ名ではなく編集画面の表示名の方を表示する
 *
 * ●注意
 * 導入前にsaveフォルダを空にする
 * (global.rpgsaveも消す、コンフィグのは残してもOK)
 *
 * 画像はPicturesフォルダに入れる
 *
 */

(function(){
	// params --------------------------------------------------------
    var parameters = PluginManager.parameters('セーブ画面');
    var Params = {};
	Params.useBackPicture1 = parameters['UseBackPicture1'] || '';
	Params.backPicture1 = parameters['BackPicture1'] || '';
	Params.useBackPicture2 = parameters['UseBackPicture2'] || '';
	Params.backPicture2 = parameters['BackPicture2'] || '';
	Params.opacity = Number(parameters['Opacity'] || 0);
	Params.drawGauge = parameters['DrawGauge'] || '';
	Params.moveLvDraw = parameters['MoveLvDraw'] || '';
	Params.fontSize1 = Number(parameters['FontSize1'] || 24);
	Params.fontSize2 = Number(parameters['FontSize2'] || 36);
	Params.color = [parameters['Color1'], parameters['Color2'],
	parameters['Color3'], parameters['Color4'], parameters['Color5']];
	Params.defalutColor = ['rgba(0,0,0,0.2)', 'rgba(0,0,0,1)',
	                       'rgba(0,0,64,0.5)', 'rgba(0,0,64,0.5)', '#00FF00'];
	// DataManager -------------------------------------------------------------
	// makeSavefileInfo
	var _DataManager_makeSavefileInfo = DataManager.makeSavefileInfo;
	DataManager.makeSavefileInfo = function() {
		var info = _DataManager_makeSavefileInfo.call(this);
		info.partyLeaderParam = $gameParty.leaderParam();
		info.mapName = $gameMap.displayName();
		return info;
	};
	// Game_Party --------------------------------------------------------------
	// leaderParam
	Game_Party.prototype.leaderParam = function() {
		var actor = this.leader();
		if (!actor) return null;
		return [actor._level, actor.hp, actor.mhp, actor.mp, actor.mmp,
		        actor.atk, actor.def, actor.mat, actor.mdf, actor.agi,
				actor.luk, actor.name()];
	};
	// Window_SavefileList -----------------------------------------------------
	// maxItems
	Window_SavefileList.prototype.maxItems = function() {
		return DataManager.maxSavefiles();
	};
    // maxVisibleItems
	Window_SavefileList.prototype.maxVisibleItems = function() {
		return 15;
	};
	// setActorWindow
	Window_SavefileList.prototype.setActorWindow = function(window) {
		this._actorWindow = window;
		this.updateActorWindow();
	};
	// updateActorWindow
	Window_SavefileList.prototype.updateActorWindow = function() {
		if (this._actorWindow){
			var id = this.index() + 1;
			this._actorWindow.setId(id);
		}
	};
	// callUpdateHelp
	var _Window_SavefileList_callUpdateHelp = Window_SavefileList.prototype.callUpdateHelp;
	Window_SavefileList.prototype.callUpdateHelp = function() {
		_Window_SavefileList_callUpdateHelp.call(this);
		if (this.active && this._actorWindow) {
			this.updateActorWindow();
		}
	};
	// standardFontSize
	Window_SavefileList.prototype.standardFontSize = function() {
		return Params.fontSize1;
	};
	// leftWidth
	Window_SavefileList.prototype.leftWidth = function() {
		return 88;
	};
	// centerWidth
	Window_SavefileList.prototype.centerWidth = function() {
		return 240;
	};
	// drawItem
	Window_SavefileList.prototype.drawItem = function(index) {
		var id = index + 1;
		var valid = DataManager.isThisGameFile(id);
		var info = DataManager.loadSavefileInfo(id);
		var rect = this.itemRect(index);
		this.resetTextColor();
		if (this._mode === 'load') {
			this.changePaintOpacity(valid);
		}
		this.backGradient(rect);
		this.drawFileId(id, rect.x + 4, rect.y);
		if (info) {
			this.changePaintOpacity(valid);
			this.drawContents(info, rect, valid);
			this.changePaintOpacity(true);
		}
	};
	// drawFileId
	Window_SavefileList.prototype.drawFileId = function(id, x, y) {
		this.drawText('File ' + id, x, y, this.leftWidth());
	};
	// backGradient
	Window_SavefileList.prototype.backGradient = function(rect) {
		var c1 = Params.color[0] || Params.defalutColor[0];
		var c2 = Params.color[1] || Params.defalutColor[1];
		var c3 = Params.color[2] || Params.defalutColor[2];
		var c4 = Params.color[3] || Params.defalutColor[3];
		var w1 = this.leftWidth();
		var w2 = rect.width - w1;
        this.contents.gradientFillRect(rect.x, rect.y, w1, 36, c1, c2);
		this.contents.gradientFillRect(rect.x+w1, rect.y, w2, 36, c3, c4);
	};
    // drawContents
	Window_SavefileList.prototype.drawContents = function(info, rect, valid) {
		var x1 = rect.x + this.leftWidth() + 6;
		var w1 = this.centerWidth();
		this.drawMapName(info, x1, rect.y, w1);
		var rx = x1 + this.centerWidth();
		var rw = rect.width - x1 - this.centerWidth() - 6;
		this.drawPlaytime(info, rx, rect.y, rw);
	};
    // drawMapName
	Window_SavefileList.prototype.drawMapName = function(info, x, y, width) {
		if (info.mapName) {
			var color = Params.color[4] || Params.defalutColor[4];
			this.changeTextColor(color);
			this.drawText(info.mapName, x, y, width);
			this.resetTextColor();
		}
	};
	// Window_Save_Actor -------------------------------------------------------
	//
	function Window_Save_Actor() {
		this.initialize.apply(this, arguments);
	}

	Window_Save_Actor.prototype = Object.create(Window_Base.prototype);
	Window_Save_Actor.prototype.constructor = Window_Save_Actor;

	// standardFontSize
	Window_Save_Actor.prototype.standardFontSize = function() {
		return Params.fontSize2;
	};
	// setId
	Window_Save_Actor.prototype.setId = function(id) {
		this.refresh(id);
	};
	// refresh
	Window_Save_Actor.prototype.refresh = function(id) {
		this.contents.clear();
		var info = DataManager.loadSavefileInfo(id);
		if (!info) return;
		var param = info.partyLeaderParam;
		var name = String(param[param.length - 1]);
		var cx = (this.contents.width - 144) / 2;
		var bx = 6;
		var by = 152;
		var lh = 36;
		var pw = 0;
		var ph = 0;
		var flag = Params.moveLvDraw === 'true';
		if (flag){
			pw += 72;
			ph += lh;
		}
		if (info.faces){
			var data = info.faces[0];
			this.drawFace(data[0], data[1], cx, 0, 144, 144);
		}

		this.drawActorName(name, param[1], param[2], bx, by + lh * 0, 200 + pw);
		this.drawActorLevel(param[0], 200, by + ph + lh * 0, flag);
		this.drawActorHp(param[1], param[2], bx, by + ph + lh * 1, 210);
		this.drawActorMp(param[3], param[4], bx, by + ph + lh * 2, 210);

		for (var i = 0; i < 6; i++) {
            this.drawItem(param, bx, by + ph + lh * (3 + i), 2 + i, 5 + i);
        }
	};
	// drawActorName
	Window_Save_Actor.prototype.drawActorName = function(name, hp, mhp, x, y, width) {
		width = width || 168;
		var rate = hp / mhp;
		this.changeTextColor(this.hpColor(rate));
		this.drawText(name, x, y, width);
	};
	// drawActorLevel
	Window_Save_Actor.prototype.drawActorLevel = function(num, x, y, flag) {
		var dx = flag ? 6 : x
		var dw = flag ? 60 : 36
		this.changeTextColor(this.systemColor());
		this.drawText(TextManager.levelA, dx, y, dw);
		this.resetTextColor();
		this.drawText(num, dx + dw, y, dw, 'right');
	};
	// drawActorHp
	Window_Save_Actor.prototype.drawActorHp = function(hp, mhp, x, y, width) {
		var rate = hp / mhp;
		width = width || 186;
		if (Params.drawGauge === 'true'){
			var color1 = this.hpGaugeColor1();
			var color2 = this.hpGaugeColor2();
			this.drawGauge(x, y, width, rate, color1, color2);
		}
		this.changeTextColor(this.systemColor());
		this.drawText(TextManager.hpA, x, y, 44);
		this.drawCurrentAndMax(hp, mhp, x, y, width,
							   this.hpColor(rate), this.normalColor());
	};
	// hpColor
	Window_Save_Actor.prototype.hpColor = function(rate) {
		if (rate === 0) {
			return this.deathColor();
		} else if (rate <= 0.25) {
			return this.crisisColor();
		} else {
			return this.normalColor();
		}
	};
    // drawActorMp
	Window_Save_Actor.prototype.drawActorMp = function(mp, mmp, x, y, width) {
		var rate = mp / mmp;
		width = width || 186;
		if (Params.drawGauge === 'true'){
			var color1 = this.mpGaugeColor1();
			var color2 = this.mpGaugeColor2();
			this.drawGauge(x, y, width, rate, color1, color2);
		}
		this.changeTextColor(this.systemColor());
		this.drawText(TextManager.mpA, x, y, 44);
		this.drawCurrentAndMax(mp, mmp, x, y, width,
							   this.normalColor(), this.normalColor());
	};
	// drawItem
	Window_Save_Actor.prototype.drawItem = function(param, x, y, paramId, paramId2) {
		this.drawParamName(x, y, paramId);
		this.drawCurrentParam(x + 180, y, param[paramId2]);
	};
	// drawParamName
	Window_Save_Actor.prototype.drawParamName = function(x, y, paramId) {
		this.changeTextColor(this.systemColor());
		this.drawText(TextManager.param(paramId), x, y, 140);
	};
    // drawCurrentParam
	Window_Save_Actor.prototype.drawCurrentParam = function(x, y, num) {
		this.resetTextColor();
		this.drawText(num, x, y, 80, 'right');
	};
	// Scene_Title -------------------------------------------------------------
	// isReady
	var _Scene_Title_isReady = Scene_Title.prototype.isReady;
	Scene_Title.prototype.isReady = function() {
		if (!this.faceLoadFlag){
			this.faceLoadFlag = true;
			DataManager.loadAllSavefileImages();
		}
		return _Scene_Title_isReady.call(this);
	}
	// Scene_File --------------------------------------------------------------
	// createBackground
	Scene_File.prototype.createBackground = function() {
		this._backgroundSprite = new Sprite();
		if (Params.useBackPicture1 === 'true'){
			this._backgroundSprite.bitmap =
			ImageManager.loadPicture(Params.backPicture1, 0);
		}else{
			this._backgroundSprite.bitmap = SceneManager.backgroundBitmap();
		}
		this.addChild(this._backgroundSprite);

		if (Params.useBackPicture2 === 'true'){
			this._backgroundSprite2 = new Sprite();
			this._backgroundSprite2.bitmap =
				ImageManager.loadPicture(Params.backPicture2, 0);
			this.addChild(this._backgroundSprite2);
		};
    };
	// create
	var _Scene_File_create = Scene_File.prototype.create;
	Scene_File.prototype.create = function() {
		_Scene_File_create.call(this);
		this.createActorWindow();
		this.setWindowOpacity();
	};
	// createListWindow
	Scene_File.prototype.createListWindow = function() {
		var x = 0;
		var y = this._helpWindow.height;
		var width = 496;
		var height = Graphics.boxHeight - y;
		this._listWindow = new Window_SavefileList(x, y, width, height);
		this._listWindow.setHandler('ok',     this.onSavefileOk.bind(this));
		this._listWindow.setHandler('cancel', this.popScene.bind(this));
		this._listWindow.select(this.firstSavefileIndex());
		this._listWindow.setTopRow(this.firstSavefileIndex() - 2);
		this._listWindow.setMode(this.mode());
		this._listWindow.refresh();
		this.addWindow(this._listWindow);
	};
	// createActorWindow
	Scene_File.prototype.createActorWindow = function() {
		var x = this._listWindow.width;
		var y = this._helpWindow.height;
		var w = Graphics.boxWidth - x;
		var h = Graphics.boxHeight - y;
		this._actorWindow = new Window_Save_Actor(x, y, w, h);
		this._listWindow.setActorWindow(this._actorWindow);
		this.addWindow(this._actorWindow);
	}
	// setWindowOpacity
	Scene_File.prototype.setWindowOpacity = function(){
	    this._helpWindow.opacity = Params.opacity;
		this._listWindow.opacity = Params.opacity;
		this._actorWindow.opacity = Params.opacity;
	}
})();