view src/luan/modules/swing/Text_component.luan @ 1906:adb77b95fa27

undo fix
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 15 Apr 2025 18:19:47 -0600
parents 49e2103ebf6a
children 1d60e0ac3b97
line wrap: on
line source

local Luan = require "luan:Luan.luan"
local error = Luan.error
local raw_set = Luan.raw_set or error()
local stringify = Luan.stringify or error()
local Utils = require "luan:swing/Utils.luan"
local fail = Utils.fail or error()
local make_metatable = Utils.make_metatable or error()
local Component = require "luan:swing/Component.luan"
local super__index = Component.__index or error()
local super__new_index = Component.__new_index or error()
local super_construct = Component.construct or error()
local new_document = require("luan:swing/Document.luan").new or error()
require "java"
local SwingLuan = require "java:luan.modules.swing.SwingLuan"
local fixTextComponent = SwingLuan.fixTextComponent
local Logging = require "luan:logging/Logging.luan"
local logger = Logging.logger "swing/Text_component"


local Text_component = {}

function Text_component.__index(component,key)
	local rtn = super__index(component,key)
	if rtn ~= fail then return rtn end
	local jcomponent = component.java
	if key == "text" then
		return jcomponent.getText()
	end
	if key == "document" then
		return component._document
	end
	if key == "selected_text" then
		return jcomponent.getSelectedText() or ""
	end
	return fail
end

function Text_component.__new_index(component,key,value)
	local rtn = super__new_index(component,key,value)
	if rtn ~= fail then return end
	local jcomponent = component.java
	if key == "text" then
		jcomponent.setText(value)
		return
	end
	if key == "document" then
		jcomponent.setDocument(value.java)
		raw_set(component,"_document",value)
		return
	end
	if key == "selected_text" then
		local document = jcomponent.getDocument()
		local start = jcomponent.getSelectionStart()
		local end_ = jcomponent.getSelectionEnd()
		if end_ > start then
			document.remove( start, end_ - start )
		end
		if #value > 0 then
			document.insertString( start, value, nil )
		end
		jcomponent.select( start, start + #value )
		return
	end
	return fail
end

Text_component.mt = make_metatable(Text_component)

function Text_component.construct(component,props)
	super_construct(component,props)
	local jcomponent = component.java
	component._document = new_document(jcomponent.getDocument())
	fixTextComponent(jcomponent)
	component.cut = jcomponent.cut
	component.copy = jcomponent.copy
	component.paste = jcomponent.paste
	component.select_all = jcomponent.selectAll
	function component.get_selection()
		return jcomponent.getSelectionStart()+1, jcomponent.getSelectionEnd()+1
	end
	function component.set_selection(start_pos,end_pos)
		end_pos = end_pos or start_pos
		jcomponent.select(start_pos-1,end_pos-1)
	end
	return component
end

return Text_component