forked from androidx/androidx
-
Notifications
You must be signed in to change notification settings - Fork 62
/
Main.jvm.kt
704 lines (659 loc) · 25.3 KB
/
Main.jvm.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.desktop.examples.example1
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.ContextMenuDataProvider
import androidx.compose.foundation.ContextMenuItem
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.VerticalScrollbar
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.mouseClickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.rememberScrollbarAdapter
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.material.BottomAppBar
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Checkbox
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.ExtendedFloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Slider
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Blue
import androidx.compose.ui.graphics.Color.Companion.Green
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.graphics.Color.Companion.Yellow
import androidx.compose.ui.graphics.ImageShader
import androidx.compose.ui.graphics.ShaderBrush
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.isCtrlPressed
import androidx.compose.ui.input.key.isMetaPressed
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerIconDefaults
import androidx.compose.ui.input.pointer.isAltPressed
import androidx.compose.ui.input.pointer.isBackPressed
import androidx.compose.ui.input.pointer.isCtrlPressed
import androidx.compose.ui.input.pointer.isForwardPressed
import androidx.compose.ui.input.pointer.isMetaPressed
import androidx.compose.ui.input.pointer.isPrimaryPressed
import androidx.compose.ui.input.pointer.isSecondaryPressed
import androidx.compose.ui.input.pointer.isShiftPressed
import androidx.compose.ui.input.pointer.isTertiaryPressed
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.input.pointer.pointerHoverIcon
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.loadImageBitmap
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.useResource
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.platform.Font
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextDecoration.Companion.Underline
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.FrameWindowScope
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowState
import androidx.compose.ui.window.launchApplication
import androidx.compose.ui.window.rememberWindowState
import androidx.compose.ui.window.singleWindowApplication
import kotlin.random.Random
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
private const val title = "Desktop Compose Elements"
val italicFont = FontFamily(
Font("NotoSans-Italic.ttf")
)
val dispatchedFonts = FontFamily(
Font("NotoSans-Italic.ttf", style = FontStyle.Italic),
Font("NotoSans-Regular.ttf", style = FontStyle.Normal)
)
private val isCtrlPressed = mutableStateOf(false)
fun main() = singleWindowApplication(
title = title,
state = WindowState(width = 1024.dp, height = 850.dp),
onPreviewKeyEvent = {
isCtrlPressed.value = it.isCtrlPressed
false
}
) {
App()
}
@Composable
private fun FrameWindowScope.App() {
val uriHandler = LocalUriHandler.current
MaterialTheme {
Scaffold(
topBar = {
WindowDraggableArea {
TopAppBar(
title = {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(
painterResource("androidx/compose/desktop/example/star.svg"),
contentDescription = "Star"
)
Text(title)
}
}
)
}
},
floatingActionButton = {
ExtendedFloatingActionButton(
text = { Text("Open URL") },
onClick = {
uriHandler.openUri("https://google.com")
}
)
},
isFloatingActionButtonDocked = true,
bottomBar = {
BottomAppBar(cutoutShape = CircleShape) {
IconButton(
onClick = {}
) {
Icon(Icons.Filled.Menu, "Menu", Modifier.size(ButtonDefaults.IconSize))
}
}
},
content = { innerPadding ->
Row(Modifier.padding(innerPadding)) {
LeftColumn(Modifier.weight(1f))
RightColumn(Modifier.width(200.dp))
}
}
)
}
}
@Composable
private fun FrameWindowScope.LeftColumn(modifier: Modifier) = Box(modifier.fillMaxSize()) {
val state = rememberScrollState()
ScrollableContent(state)
VerticalScrollbar(
rememberScrollbarAdapter(state),
Modifier.align(Alignment.CenterEnd).fillMaxHeight()
)
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun FrameWindowScope.ScrollableContent(scrollState: ScrollState) {
val amount = remember { mutableStateOf(0f) }
val animation = remember { mutableStateOf(true) }
Column(Modifier.fillMaxSize().verticalScroll(scrollState)) {
val info = "${window.renderApi} (${window.windowHandle})"
Text(
text = "Привет! 你好! Desktop Compose use $info: ${amount.value}",
color = Color.Black,
modifier = Modifier
.background(Color.Blue)
.height(56.dp)
.wrapContentSize(Alignment.Center)
)
val inlineIndicatorId = "indicator"
Text(
text = buildAnnotatedString {
append("The quick ")
if (animation.value) {
appendInlineContent(inlineIndicatorId)
}
pushStyle(
SpanStyle(
color = Color(0xff964B00),
shadow = Shadow(Color.Green, offset = Offset(1f, 1f))
)
)
append("brown fox")
pop()
pushStyle(SpanStyle(background = Color.Yellow))
append(" 🦊 ate a ")
pop()
pushStyle(SpanStyle(fontSize = 30.sp, textDecoration = Underline))
append("zesty hamburgerfons")
pop()
append(" 🍔.\nThe 👩👩👧👧 laughed.")
addStyle(SpanStyle(color = Color.Green), 25, 35)
},
color = Color.Black,
inlineContent = mapOf(
inlineIndicatorId to InlineTextContent(
Placeholder(
width = 1.em,
height = 1.em,
placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline
)
) {
CircularProgressIndicator(Modifier.padding(end = 3.dp))
}
)
)
val loremColors = listOf(
Color.Black,
Color.Yellow,
Color.Green,
Color.Blue
)
var loremColor by remember { mutableStateOf(0) }
val loremDecorations = listOf(
TextDecoration.None,
TextDecoration.Underline,
TextDecoration.LineThrough
)
val lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do" +
" eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad" +
" minim veniam, quis nostrud exercitation ullamco laboris nisi ut" +
" aliquipex ea commodo consequat. Duis aute irure dolor in reprehenderit" +
" in voluptate velit esse cillum dolore eu fugiat nulla pariatur." +
" Excepteur" +
" sint occaecat cupidatat non proident, sunt in culpa qui officia" +
" deserunt mollit anim id est laborum."
var loremDecoration by remember { mutableStateOf(0) }
Text(
text = lorem,
color = loremColors[loremColor],
textAlign = TextAlign.Center,
textDecoration = loremDecorations[loremDecoration],
modifier = Modifier.clickable {
if (loremColor < loremColors.size - 1) {
loremColor += 1
} else {
loremColor = 0
}
if (loremDecoration < loremDecorations.size - 1) {
loremDecoration += 1
} else {
loremDecoration = 0
}
}
)
Text(
text = lorem,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Row {
Box(modifier = Modifier.size(200.dp, 200.dp).border(1.dp, Black)) {
BrushTextGradient(lorem)
}
Box(modifier = Modifier.size(200.dp, 200.dp).border(1.dp, Black)) {
BrushTextImage(lorem)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Text(
"Default",
)
Text(
"SansSerif",
fontFamily = FontFamily.SansSerif
)
Text(
"Serif",
fontFamily = FontFamily.Serif
)
Text(
"Monospace",
fontFamily = FontFamily.Monospace
)
Text(
"Cursive",
fontFamily = FontFamily.Cursive
)
}
var overText by remember { mutableStateOf("Move mouse over text:") }
Text(overText, style = TextStyle(letterSpacing = 10.sp))
SelectionContainer {
Text(
text = "fun <T : Comparable<T>> List<T>.quickSort(): List<T> = when {\n" +
" size < 2 -> this\n" +
" else -> {\n" +
" val pivot = first()\n" +
" val (smaller, greater) = drop(1).partition { it <= pivot }\n" +
" smaller.quickSort() + pivot + greater.quickSort()\n" +
" }\n" +
"}",
fontFamily = italicFont,
modifier = Modifier
.padding(10.dp)
.onPointerEvent(PointerEventType.Move) {
val position = it.changes.first().position
overText = "Move position: $position"
}
.onPointerEvent(PointerEventType.Enter) {
overText = "Over enter"
}
.onPointerEvent(PointerEventType.Exit) {
overText = "Over exit"
}
)
}
Text(
text = buildAnnotatedString {
append("resolved: NotoSans-Regular.ttf ")
pushStyle(
SpanStyle(
fontStyle = FontStyle.Italic
)
)
append("NotoSans-italic.ttf.")
},
fontFamily = dispatchedFonts,
)
Row(verticalAlignment = Alignment.CenterVertically) {
Button(
modifier = Modifier.padding(4.dp).pointerHoverIcon(PointerIconDefaults.Hand),
onClick = {
amount.value++
}
) {
Text("Base")
}
var clickableText by remember { mutableStateOf("Click me!") }
@OptIn(ExperimentalFoundationApi::class)
Text(
modifier = Modifier.mouseClickable(
onClick = {
clickableText = buildString {
append("Buttons pressed:\n")
append("primary: ${buttons.isPrimaryPressed}\t")
append("secondary: ${buttons.isSecondaryPressed}\t")
append("tertiary: ${buttons.isTertiaryPressed}\t")
append("primary: ${buttons.isPrimaryPressed}\t")
append("back: ${buttons.isBackPressed}\t")
append("forward: ${buttons.isForwardPressed}\t")
append("\n\nKeyboard modifiers pressed:\n")
append("alt: ${keyboardModifiers.isAltPressed}\t")
append("ctrl: ${keyboardModifiers.isCtrlPressed}\t")
append("meta: ${keyboardModifiers.isMetaPressed}\t")
append("shift: ${keyboardModifiers.isShiftPressed}\t")
}
}
),
text = clickableText
)
}
Row(
modifier = Modifier.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Row {
Column {
Switch(
animation.value,
onCheckedChange = {
animation.value = it
}
)
Row(
modifier = Modifier.padding(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
animation.value,
onCheckedChange = {
animation.value = it
}
)
Text("Animation")
}
}
Button(
modifier = Modifier.padding(4.dp),
onClick = {
@OptIn(DelicateCoroutinesApi::class)
GlobalScope.launchApplication {
Window(
onCloseRequest = ::exitApplication,
state = rememberWindowState(size = DpSize(400.dp, 200.dp)),
onPreviewKeyEvent = {
if (it.key == Key.Escape) {
exitApplication()
true
} else {
false
}
}
) {
Animations(isCircularEnabled = animation.value)
}
}
}
) {
Text("Window")
}
}
Animations(isCircularEnabled = animation.value)
}
Slider(
value = amount.value / 100f,
onValueChange = { amount.value = (it * 100) }
)
val dropDownMenuExpanded = remember { mutableStateOf(false) }
Button(onClick = { dropDownMenuExpanded.value = true }) {
Text("Expand Menu")
}
DropdownMenu(
expanded = dropDownMenuExpanded.value,
onDismissRequest = {
dropDownMenuExpanded.value = false
println("OnDismissRequest")
}
) {
DropdownMenuItem(modifier = Modifier, onClick = {
println("Item 1 clicked")
}) {
Text("Item 1")
}
DropdownMenuItem(modifier = Modifier, onClick = {
println("Item 2 clicked")
}) {
Text("Item 2")
}
DropdownMenuItem(modifier = Modifier, onClick = {
println("Item 3 clicked")
}) {
Text("Item 3")
}
}
TextField(
value = amount.value.toString(),
onValueChange = { amount.value = it.toFloatOrNull() ?: 42f },
label = { Text(text = "Input1") }
)
val (focusItem1, focusItem2) = FocusRequester.createRefs()
val text = remember {
mutableStateOf("Hello \uD83E\uDDD1\uD83C\uDFFF\u200D\uD83E\uDDB0")
}
ContextMenuDataProvider(
items = {
listOf(ContextMenuItem("Clear") { text.value = ""; focusItem1.requestFocus() })
}
) {
TextField(
value = text.value,
onValueChange = { text.value = it },
label = { Text(text = "Input2") },
placeholder = {
Text(text = "Important input")
},
maxLines = 1,
modifier = Modifier.onPreviewKeyEvent {
when {
(it.isMetaPressed && it.key == Key.Enter) -> {
if (it.isShiftPressed) {
text.value = "Cleared with shift!"
} else {
text.value = "Cleared!"
}
true
}
else -> false
}
}.focusRequester(focusItem1)
.focusProperties {
next = focusItem2
}
)
}
var text2 by remember {
val initText = buildString {
(1..1000).forEach {
append("$it\n")
}
}
mutableStateOf(initText)
}
TextField(
text2,
modifier = Modifier
.height(200.dp)
.focusRequester(focusItem2)
.focusProperties {
previous = focusItem1
},
onValueChange = { text2 = it }
)
Row {
Image(
painterResource("androidx/compose/desktop/example/circus.jpg"),
"Localized description",
Modifier.size(200.dp)
)
Icon(
painterResource("androidx/compose/desktop/example/ic_baseline_deck_24.xml"),
"Localized description",
Modifier.size(100.dp).align(Alignment.CenterVertically),
tint = Color.Blue.copy(alpha = 0.5f)
)
}
Box(
modifier = Modifier.size(150.dp).background(Color.Gray).pointerHoverIcon(
if (isCtrlPressed.value) PointerIconDefaults.Hand else PointerIconDefaults.Default
)
) {
Box(
modifier = Modifier.offset(20.dp, 20.dp).size(100.dp).background(Color.Blue).pointerHoverIcon(
if (isCtrlPressed.value) PointerIconDefaults.Crosshair else PointerIconDefaults.Text,
)
) {
Text("pointerHoverIcon test with Ctrl")
}
}
}
}
@Composable
fun Animations(isCircularEnabled: Boolean) = Row {
if (isCircularEnabled) {
CircularProgressIndicator(Modifier.padding(10.dp))
}
val enabled = remember { mutableStateOf(true) }
val color by animateColorAsState(
if (enabled.value) Color.Green else Color.Red,
animationSpec = TweenSpec(durationMillis = 2000)
)
MaterialTheme {
Box(
Modifier
.size(70.dp)
.clickable { enabled.value = !enabled.value }
.background(color)
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun RightColumn(modifier: Modifier) = Box {
val state = rememberLazyListState()
val itemCount = 100000
val heights = remember {
val random = Random(24)
(0 until itemCount).map { random.nextFloat() }
}
LazyColumn(modifier.graphicsLayer(alpha = 0.5f), state = state) {
items((0 until itemCount).toList()) { i ->
val itemHeight = 20.dp + 20.dp * heights[i]
Text(i.toString(), Modifier.graphicsLayer(alpha = 0.5f).height(itemHeight))
}
}
VerticalScrollbar(
rememberScrollbarAdapter(state),
Modifier.align(Alignment.CenterEnd)
)
}
@OptIn(ExperimentalTextApi::class)
@Composable
fun BrushTextGradient(text: String) {
Text(
text = text,
style = TextStyle(
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
brush = Brush.linearGradient(
colors = listOf(Red, Yellow, Green, Blue)
)
)
)
}
@OptIn(ExperimentalTextApi::class)
@Composable
fun BrushTextImage(text: String) {
val image = remember {
useResource("androidx/compose/desktop/example/tray.png", ::loadImageBitmap)
}
Text(
text = text,
style = TextStyle(
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
brush = ShaderBrush(
ImageShader(image, TileMode.Repeated, TileMode.Repeated)
)
)
)
}