TornadoFx Undecorated window goes fullscreen when restored from task bar - kotlin

I've been trying out Tornadofx. trying to create a custom title-bar, here's the code I'm currently trying
fun main(args: Array<String>) {
launch<MyApp>(args)
}
class MyApp : App(Title::class) {
override fun start(stage: Stage) {
stage.initStyle(StageStyle.UNDECORATED)
stage.minWidth = 600.0
stage.minHeight = 450.0
stage.isMaximized = false
super.start(stage)
}
}
class Title : View() {
private var xOffset = 0.0
private var yOffset = 0.0
private var screenBounds: Rectangle2D = Screen.getPrimary().visualBounds
private var originalBounds: Rectangle2D = Rectangle2D.EMPTY
init {
primaryStage.isMaximized = false
}
override val root = borderpane {
onMousePressed = EventHandler { ev ->
xOffset = primaryStage.x - ev.screenX
yOffset = primaryStage.y - ev.screenY
}
onMouseDragged = EventHandler { ev ->
primaryStage.x = xOffset + ev.screenX
primaryStage.y = yOffset + ev.screenY
}
center = label("Forms")
right = hbox {
button("Mi") {
action {
with(primaryStage) { isIconified = true }
}
}
button("Ma") {
action {
if (primaryStage.isMaximized) {
with(primaryStage) {
x = originalBounds.minX
y = originalBounds.minY
width = originalBounds.width
height = originalBounds.height
isMaximized = false
}
text = "Ma"
} else {
with(primaryStage) {
originalBounds = Rectangle2D(x, y, width, height)
x = screenBounds.minX
y = screenBounds.minY
width = screenBounds.width
height = screenBounds.height
isMaximized = true
}
text = "Re"
}
}
}
button("X") {
action {
app.stop()
println("exiting")
exitProcess(0)
}
}
}
}
}
the following work without problems
close
maximize, restore
restored window minimized, then open from taskbar
but when a maximized window is minimized to taskbar, then open from taskbar, it goes full screen(taskbar is hidden)
how do i fix this behavior, is there any part of my code that is wrong, needs change, or in need of any inclusions?
my configuration is Windows 10 64bit, Java 11.0.2, Kotlin 1.4.21, JavaFx 11.0.2, TornadoFx 1.7.20

I think this is a general problem in JavaFX (I mean not specific with TornadoFX).
The root cause for this is because of setting the maximized property of stage to true. Not sure what JavaFX internally does, but when you open the window from task bar and if the maximized value is true, then it renders in full screen mode.
You can fix this in two ways.
Approach #1:
When the window is opened from task bar, the iconfied property will turn off, set the stage dimensions again to screen bounds if maximized is true.
primaryStage.iconifiedProperty().addListener((obs,old,iconified)->{
if(!iconified && primaryStage.isMaximized()){
primaryStage.setWidth(screenBounds.getWidth());
primaryStage.setHeight(screenBounds.getHeight());
}
});
Approach #2:
Don't rely on the maximized property of the Stage. I believe you need that property to toggle the window dimensions. So instead maintain a instance variable to handle that.
boolean maximized = false;
ma.setOnAction(e -> {
if (maximized) {
// Set stage to original bounds
maximized = false;
ma.setText("Ma");
} else {
// Set stage to screen bounds
maximized = false;
ma.setText("Re");
}
});
A full working demo is below with both the approaches. You can decide which way to go based on your other requirments.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class UndecoratedWindowFullScreenDemo extends Application {
private double xOffset = 0.0;
private double yOffset = 0.0;
private Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
private Rectangle2D originalBounds = Rectangle2D.EMPTY;
private boolean maximized = false;
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
root.setStyle("-fx-background-color:pink;");
Scene scene = new Scene(root, 600, 450);
primaryStage.setScene(scene);
Label label = new Label("Forums");
Button mi = new Button("Mi");
Button ma = new Button("Ma");
Button x = new Button("X");
HBox pane = new HBox(mi, ma, x);
pane.setPadding(new Insets(3));
pane.setSpacing(5);
root.setCenter(label);
root.setRight(pane);
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.setMinWidth(600);
primaryStage.setMinHeight(450);
primaryStage.setMaximized(false);
primaryStage.show();
root.setOnMousePressed(e -> {
xOffset = primaryStage.getX() - e.getScreenX();
yOffset = primaryStage.getY() - e.getScreenY();
});
root.setOnMouseDragged(e -> {
primaryStage.setX(xOffset + e.getScreenX());
primaryStage.setY(yOffset + e.getScreenY());
});
mi.setOnAction(e -> primaryStage.setIconified(true));
/* Use this approach if you want to go with the Stage maximized property */
// approach1(primaryStage, ma);
/* Use this approach if you want to avoid Stage maximized property and maintain a instance variable */
approach2(primaryStage, ma);
}
private void approach1(Stage primaryStage, Button ma) {
primaryStage.iconifiedProperty().addListener((obs, old, iconified) -> {
if (!iconified && primaryStage.isMaximized()) {
primaryStage.setWidth(screenBounds.getWidth());
primaryStage.setHeight(screenBounds.getHeight());
}
});
ma.setOnAction(e -> {
if (primaryStage.isMaximized()) {
primaryStage.setX(originalBounds.getMinX());
primaryStage.setY(originalBounds.getMinY());
primaryStage.setWidth(originalBounds.getWidth());
primaryStage.setHeight(originalBounds.getHeight());
primaryStage.setMaximized(false);
ma.setText("Ma");
} else {
originalBounds = new Rectangle2D(primaryStage.getX(), primaryStage.getY(), primaryStage.getWidth(), primaryStage.getHeight());
primaryStage.setX(screenBounds.getMinX());
primaryStage.setY(screenBounds.getMinY());
primaryStage.setWidth(screenBounds.getWidth());
primaryStage.setHeight(screenBounds.getHeight());
primaryStage.setMaximized(true);
ma.setText("Re");
}
});
}
private void approach2(Stage primaryStage, Button ma) {
ma.setOnAction(e -> {
if (maximized) {
primaryStage.setX(originalBounds.getMinX());
primaryStage.setY(originalBounds.getMinY());
primaryStage.setWidth(originalBounds.getWidth());
primaryStage.setHeight(originalBounds.getHeight());
maximized = false;
ma.setText("Ma");
} else {
originalBounds = new Rectangle2D(primaryStage.getX(), primaryStage.getY(), primaryStage.getWidth(), primaryStage.getHeight());
primaryStage.setX(screenBounds.getMinX());
primaryStage.setY(screenBounds.getMinY());
primaryStage.setWidth(screenBounds.getWidth());
primaryStage.setHeight(screenBounds.getHeight());
maximized = true;
ma.setText("Re");
}
});
}
}

There are two changes that were needed to solve the problem
The actual problem was that if isMaximized is set to true the app goes full screen when being open from task(minimized) even though isFullScreen property is separately available
Adding a maximized property listener so that we can invalidate if the isMaximized were to be ever modified by other means(like double clicking on title bar in Linux etc)
// CHANGE 1
stage.maximizedProperty().addListener { _, _, newValue ->
if (newValue) stage.isMaximized = false
}
by having a separate maximized instead of using isMaximized
// CHANGE 2
private var maximized: Boolean = false // <- here
if (maximized) { // <- here
// restore the window by setting bounds of original size
maximized = false // <- here
text = "Ma"
} else {
// maximize window by setting bounds from screen size
maximized = true // <- and here
text = "Re"
}
Bonus : use isFocusTraversable = false to make buttons that don't focus with keyboard traversal
Final solution
fun main(args: Array<String>) {
launch<MyApp>(args)
}
class MyApp : App(Window::class, Styles::class) {
override fun start(stage: Stage) {
stage.initStyle(StageStyle.UNDECORATED)
stage.minWidth = 600.0
stage.minHeight = 450.0
stage.width = 600.0
stage.height = 450.0
// CHANGE 1
stage.maximizedProperty().addListener { _, _, newValue ->
if (newValue) stage.isMaximized = false
}
stage.isMaximized = false
super.start(stage)
}
}
class Window : View() {
override val root = borderpane {
top = Title().root
}
}
class Title : View() {
// CHANGE 2
private var maximized: Boolean = false // <- here
private var xOffset = 0.0
private var yOffset = 0.0
private var screenBounds: Rectangle2D = Screen.getPrimary().visualBounds
private var originalBounds: Rectangle2D = Rectangle2D.EMPTY
init {
primaryStage.isMaximized = false
}
override val root = hbox {
hgrow = Priority.ALWAYS
onMousePressed = EventHandler { ev ->
xOffset = primaryStage.x - ev.screenX
yOffset = primaryStage.y - ev.screenY
}
onMouseDragged = EventHandler { ev ->
primaryStage.x = xOffset + ev.screenX
primaryStage.y = yOffset + ev.screenY
}
val l1 = hbox {
hgrow = Priority.ALWAYS
alignment = Pos.CENTER
label("Forms")
}
add(l1)
l1.requestFocus()
button("Mi") {
id = "min"
action {
with(primaryStage) { isIconified = true }
}
isFocusTraversable = false
}
button("Ma") {
id = "max"
action {
if (maximized) { // <- here
with(primaryStage) {
x = originalBounds.minX
y = originalBounds.minY
width = originalBounds.width
height = originalBounds.height
maximized = false // <- here
}
text = "Ma"
} else {
with(primaryStage) {
originalBounds = Rectangle2D(x, y, width, height)
x = screenBounds.minX
y = screenBounds.minY
width = screenBounds.width
height = screenBounds.height
maximized = true // <- and here
}
text = "Re"
}
l1.requestFocus()
}
isFocusTraversable = false
}
button("X") {
id = "close"
action {
app.stop()
println("exiting")
exitProcess(0)
}
isFocusTraversable = false
}
}
}

Related

Reset State Variables To Initial Values xcode

What is the best way to go about resetting state variables, using a button. I've tried a load of different funcs but none work.
I'm trying to use this button:
primaryButton: .destructive(Text("Delete")) {
Code
},secondaryButton:
.cancel()
To reset these State variables:
#State var statsValue1 = 0
#State var statsValue2 = 0
#State var statsValue3 = 0
#State var statsValue4 = 0
#State var statsValue5 = 0
#State var statsValue6 = 0
(which are in the main content view)
How about using a view model, the #Published property wrapper notifies about any changes of the model and the reset function creates a new instance
struct Model {
var value1 = 0
var value2 = 0
var value3 = 0
}
class ViewModel : ObservableObject {
#Published var model = Model()
func reset() {
model = Model()
}
}
and a simple test logic in the content view
struct ContentView : View {
#StateObject var viewModel = ViewModel()
var body : some View {
VStack(spacing: 20) {
Text("Value 1: \(viewModel.model.value1)")
Text("Value 2: \(viewModel.model.value2)")
Text("Value 3: \(viewModel.model.value3)")
Divider()
Button ( "Delete", role: .destructive, action: viewModel.reset )
Button { viewModel.model.value1 += 1 } label: { Text("Increment value 1") }
Button { viewModel.model.value2 += 1 } label: { Text("Increment value 2") }
Button { viewModel.model.value3 += 1 } label: { Text("Increment value 3") }
}
}
}

Kotlin Tornadofx FilterList String out of range

I am trying to learn tornadofx and i have come across an error i cant figure out how to solve sadly I am using the filterwhen fun and it works great however when i filter the data i get the error handler telling me i have a string out of range and it happens randomly often when i delete a char from the textfield i know the code is a mess :D
enter code hereclass CenterView : View("My View") {
private val ExcelHandler: ExcelController by inject()
private var content = mutableListOf<Products>().observable()
private var rowcounter = SimpleIntegerProperty()
private var oktorun = SimpleBooleanProperty(true)
val table = TableView<Products>()
val data = SortedFilteredList(content).bindTo(table)
private var Accounts = mutableListOf<String>().observable()
override val root = borderpane() {
bottom{
hbox(10) {
style{
padding = box(10.px)
alignment = Pos.CENTER
}
button("Import"){
addClass(Styles.btmDesign)
style{
backgroundColor += Color.PURPLE
fontFamily = "Comic Sans MS"
}
useMaxWidth = true
enableWhen(oktorun)
action {
oktorun.value = false
runAsync {
ExcelHandler.readExcel("data/test.xlsx")
} ui { loadedText ->
content.isEmpty()
content.addAll(loadedText.observable())
rowcounter.value = loadedText.count()
Accounts.addAll(loadedText.map { it.Account }.toList().distinct()
.observable())
oktorun.value = true
}
}
}
hbox{
label("Rows ")
{
style{
fontSize = 20.px
fontWeight = FontWeight.BOLD
}
}
label {
style{
fontSize = 20.px
fontWeight = FontWeight.BOLD
textFill = Color.GREEN
}
bind(rowcounter)
}
}
textfield {
promptText = "Filter"
data.filterWhen(textProperty()) { query, item ->
item.Account!!.contains(query, ignoreCase = true)
}
}
}
left{
listview(Accounts) {
style{
padding = box(20.px)
fontSize = 20.px
fontWeight = FontWeight.BOLD
}
}
}
center{
style{
prefWidth = 100.px
alignment = Pos.CENTER
padding = box(20.px)
}
tableview(data) {
isEditable = true
style{
fontSize =20.px
fontWeight = FontWeight.EXTRA_BOLD
}
column("External", Products::ExternalProperty)
column("ItemRelation", Products::ItemRelationProperty)
column("Account",Products::AccountProperty)
column("Price", Products::AmmountProperty)
column("currency", Products::ValutaProperty)
column("Date", Products::DateProperty)
column("Status", Products::StatusProperty)
enableDirtyTracking()
columnResizePolicy = SmartResize.POLICY
}.multiSelect(true)
}
right {
}
}
}
}
Thank you very much for your time!
the error is
java.lang.StringIndexOutOfBoundsException: String index out of range:
3 at java.lang.String.charAt(String.java:658) at
com.sun.glass.ui.win.WinTextRangeProvider.GetBoundingRectangles(WinTextRangeProvider.java:314)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at
com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)

wxwidget - issue of wxEVT_LEAVE_WINDOW event

I'd like to implement a card style UI(as the screen shot), card is using a wxPanel as a container, a static text and a static bmp in the panel. the card will zoom in and color changed when mouse on it, when the mouse leave the card, size and color will recover as normal state. I add some logic in onEnter and onLeave of wxPanel to handle zoom and color change. the card works fine in most of cases, but if mouse move quickly, multiple cards will be selected. From output log, it seems the issue happens in OnLeave, !GetClientRect().Contains(event.GetPosition()) = false, even the mouse actually has been out of the rect of the card. how can the card work as expected even mouse move quickly?
enter image description here
void TypeCard::OnEnter(wxMouseEvent& event) {
wxRect rect = GetClientRect();
wxPoint pnt = event.GetPosition();
TRACELOG_WARNING("###### On Enter left=%d top=%d width=%d height=%d", rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
TRACELOG_WARNING("&&&&&& On Enter x=%d y=%d", pnt.x, pnt.y);
if (GetClientRect().Contains(event.GetPosition()) && !selected_ ) {
TRACELOG_WARNING("&&&&&&On Enter = true");
if (m_bZoomEnabled) {
ZoomCard(zoom_in, 5, 5);
}
selected_ = true;
} else {
TRACELOG_WARNING("*****************************************************On Enter = false selected_ = %d", (int)selected_ );
}
// have_focus_ = true;
Refresh(false);
Update();
event.Skip();
}
void TypeCard::OnLeave(wxMouseEvent& event) {
wxRect rect = GetClientRect();
wxPoint pnt = event.GetPosition();
TRACELOG_WARNING("###### On OnLeave left=%d top=%d width=%d height=%d", rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
TRACELOG_WARNING("&&&&&& On OnLeave x=%d y=%d", pnt.x, pnt.y);
// if (!GetClientRect().Contains(event.GetPosition())) {
if (!rect.Contains(pnt)) {
if (m_bZoomEnabled) {
ZoomCard(zoom_out, 5, 5);
}
selected_ = false;
} else {
TRACELOG_WARNING("*****************************************************On OnLeave = false");
}
if (!selected_) {
// have_focus_ = false;
Refresh(false);
Update();
}
event.Skip();
}
void TypeCard::OnPaint(wxPaintEvent& event) {
wxPaintDC dc(this);
wxColour colour = selected_ ? CARD_SELECT_BACKGROUND_COLOUR : COMPONENT_UNSELECT_BACKGROUND_COLOUR;
wxCursor cur = selected_ ? wxCURSOR_HAND : wxCURSOR_ARROW;
dc.SetPen(wxPen(colour));
dc.SetBrush(wxBrush(colour));
this->SetCursor(cur);
const wxWindowList& list = this->GetChildren();
for (wxWindowList::compatibility_iterator node = list.GetFirst(); node; node = node->GetNext()) {
wxWindow* current = node->GetData();
if (current) {
current->SetBackgroundColour(colour);
current->SetCursor(cur);
}
}
dc.DrawRectangle(0, 0, this->GetSize().GetWidth(), GetSize().GetHeight());
}

android expandableListView animate slide up?

I want to animate slide down and slide up on expandablelistview when I click the groupItem.Then I have finish the slide down.
public class ExpandAnimation extends Animation {
private static final String TAG = "ExpandAnimation";
private View mAnimatedView;
private LayoutParams mViewLayoutParams;
private int mMarginStart, mMarginEnd;
private boolean mIsVisibleAfter = false;
private boolean mWasEndedAlready = false;
/**
* Initialize the animation
* #param view The layout we want to animate
* #param duration The duration of the animation, in ms
*/
public ExpandAnimation(View view, int duration) {
setDuration(duration);
mAnimatedView = view;
mViewLayoutParams = (LayoutParams) view.getLayoutParams();
// if the bottom margin is 0,
// then after the animation will end it'll be negative, and invisible.
mIsVisibleAfter = (mViewLayoutParams.bottomMargin == 0);
mMarginStart = mViewLayoutParams.bottomMargin;
Log.i(TAG, "mMarginStart:>>>>>>>"+mMarginStart);
mMarginEnd = (mMarginStart == 0 ? (0- view.getHeight()) : 0);
Log.i(TAG, "mMarginEnd:>>>>>>>"+mMarginEnd);
view.setVisibility(View.VISIBLE);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
Log.i(TAG, "applyTransformation-->"+interpolatedTime);
if (interpolatedTime < 1.0f) {
// Calculating the new bottom margin, and setting it
mViewLayoutParams.bottomMargin = mMarginStart
+ (int) ((mMarginEnd - mMarginStart) * interpolatedTime);
// Invalidating the layout, making us seeing the changes we made
mAnimatedView.requestLayout();
// Making sure we didn't run the ending before (it happens!)
} else if (!mWasEndedAlready) {
mViewLayoutParams.bottomMargin = mMarginEnd;
mAnimatedView.requestLayout();
if (mIsVisibleAfter) {
mAnimatedView.setVisibility(View.GONE);
}
mWasEndedAlready = true;
}
}
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Log.i(TAG, "getChildView");
#SuppressWarnings("unchecked")
String text = ((Map<String, String>) getChild(groupPosition,
childPosition)).get("child");
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child, null);
}
View toolbar = convertView.findViewById(R.id.toolbar);
setAnimationView(toolbar);
((LinearLayout.LayoutParams) toolbar.getLayoutParams()).bottomMargin = -75;
toolbar.setVisibility(View.GONE);
ExpandAnimation expandAni = new ExpandAnimation(toolbar, 1000);
toolbar.startAnimation(expandAni);
TextView tv = (TextView) convertView.findViewById(R.id.childTo);
tv.setText(text);
return convertView;
}
But when I click the groupItem to collapse the group,it doesn't call the getChildView() method.So how can I to call the getChildView() and let it slide up?
I believe that you want to extend BaseExpandableListAdapter if you want to call (or #Override) getChildView.
http://developer.android.com/reference/android/widget/BaseExpandableListAdapter.html

air process adt flex

I have two air applications and installed them in desktop and executed them and two air processes are listed in taskbar manager.Now how can I execute some method of one air application from another air application?
Use LocalConnection.
You can Host a Connection in one AIR application and connect from the the other AIR guy... From there - you can call methods.
BEWARE: LocalConnection can be a little tricky and odd (for example, connections are global and the names can't overlap).
From the Example Doc listed above....
// Code in LocalConnectionSenderExample.as
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.LocalConnection;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.StatusEvent;
import flash.text.TextFieldAutoSize;
public class LocalConnectionSenderExample extends Sprite {
private var conn:LocalConnection;
// UI elements
private var messageLabel:TextField;
private var message:TextField;
private var sendBtn:Sprite;
public function LocalConnectionSenderExample() {
buildUI();
sendBtn.addEventListener(MouseEvent.CLICK, sendMessage);
conn = new LocalConnection();
conn.addEventListener(StatusEvent.STATUS, onStatus);
}
private function sendMessage(event:MouseEvent):void {
conn.send("myConnection", "lcHandler", message.text);
}
private function onStatus(event:StatusEvent):void {
switch (event.level) {
case "status":
trace("LocalConnection.send() succeeded");
break;
case "error":
trace("LocalConnection.send() failed");
break;
}
}
private function buildUI():void {
const hPadding:uint = 5;
// messageLabel
messageLabel = new TextField();
messageLabel.x = 10;
messageLabel.y = 10;
messageLabel.text = "Text to send:";
messageLabel.autoSize = TextFieldAutoSize.LEFT;
addChild(messageLabel);
// message
message = new TextField();
message.x = messageLabel.x + messageLabel.width + hPadding;
message.y = 10;
message.width = 120;
message.height = 20;
message.background = true;
message.border = true;
message.type = TextFieldType.INPUT;
addChild(message);
// sendBtn
sendBtn = new Sprite();
sendBtn.x = message.x + message.width + hPadding;
sendBtn.y = 10;
var sendLbl:TextField = new TextField();
sendLbl.x = 1 + hPadding;
sendLbl.y = 1;
sendLbl.selectable = false;
sendLbl.autoSize = TextFieldAutoSize.LEFT;
sendLbl.text = "Send";
sendBtn.addChild(sendLbl);
sendBtn.graphics.lineStyle(1);
sendBtn.graphics.beginFill(0xcccccc);
sendBtn.graphics.drawRoundRect(0, 0,
(sendLbl.width + 2 + hPadding + hPadding), (sendLbl.height + 2), 5, 5);
sendBtn.graphics.endFill();
addChild(sendBtn);
}
}
}
// Code in LocalConnectionReceiverExample.as
package {
import flash.display.Sprite;
import flash.net.LocalConnection;
import flash.text.TextField;
public class LocalConnectionReceiverExample extends Sprite {
private var conn:LocalConnection;
private var output:TextField;
public function LocalConnectionReceiverExample() {
buildUI();
conn = new LocalConnection();
conn.client = this;
try {
conn.connect("myConnection");
} catch (error:ArgumentError) {
trace("Can't connect...the connection name is already
being used by another SWF");
}
}
public function lcHandler(msg:String):void {
output.appendText(msg + "\n");
}
private function buildUI():void {
output = new TextField();
output.background = true;
output.border = true;
output.wordWrap = true;
addChild(output);
}
}
}