forked from hellohublot/native-kline-view
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHTKLineContainerView.java
More file actions
558 lines (477 loc) · 25.2 KB
/
HTKLineContainerView.java
File metadata and controls
558 lines (477 loc) · 25.2 KB
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
package com.github.fujianlian.klinechart.container;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import com.facebook.react.bridge.*;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import com.github.fujianlian.klinechart.HTKLineConfigManager;
import com.github.fujianlian.klinechart.KLineChartView;
import com.github.fujianlian.klinechart.KLineEntity;
import com.github.fujianlian.klinechart.RNKLineView;
import com.github.fujianlian.klinechart.HTKLineTargetItem;
import com.github.fujianlian.klinechart.formatter.DateFormatter;
public class HTKLineContainerView extends RelativeLayout {
private ThemedReactContext reactContext;
public HTKLineConfigManager configManager = new HTKLineConfigManager();
public KLineChartView klineView;
public HTShotView shotView;
public HTKLineContainerView(ThemedReactContext context) {
super(context);
this.reactContext = context;
klineView = new KLineChartView(getContext(), configManager);
klineView.setGridColumns(5);
klineView.setGridRows(3);
klineView.setChildDraw(0);
klineView.setDateTimeFormatter(new DateFormatter());
klineView.configManager = configManager;
addView(klineView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ViewGroup willShotView = (ViewGroup)getParent();
if (shotView == null) {
shotView = new HTShotView(getContext(), willShotView);
shotView.setEnabled(false);
shotView.dimension = 300;
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(shotView.dimension, shotView.dimension);
layoutParams.setMargins(50, 50, 0, 0);
((ViewGroup)willShotView.getParent().getParent()).addView(shotView, layoutParams);
}
}
public void reloadConfigManager() {
klineView.changeMainDrawType(klineView.configManager.primaryStatus);
klineView.changeSecondDrawType(klineView.configManager.secondStatus);
klineView.setMainDrawLine(klineView.configManager.isMinute);
klineView.setPointWidth(klineView.configManager.itemWidth);
klineView.setCandleWidth(klineView.configManager.candleWidth);
if (klineView.configManager.fontFamily.length() > 0) {
klineView.setTextFontFamily(klineView.configManager.fontFamily);
}
klineView.setTextColor(klineView.configManager.textColor);
klineView.setTextSize(klineView.configManager.rightTextFontSize);
klineView.setMTextSize(klineView.configManager.candleTextFontSize);
klineView.setMTextColor(klineView.configManager.candleTextColor);
klineView.reloadColor();
int previousScrollX = klineView.getScrollOffset();
klineView.notifyChanged();
if (klineView.configManager.shouldAdjustScrollPosition) {
// 调整滚动位置以补偿新增的数据
int newScrollX = previousScrollX + klineView.configManager.scrollPositionAdjustment;
klineView.setScrollX(newScrollX);
} else if (klineView.configManager.shouldScrollToEnd) {
int scrollToEnd = klineView.getMaxScrollX() - klineView.getWidth();
klineView.setScrollX(scrollToEnd);
}
final int id = this.getId();
configManager.onDrawItemDidTouch = new Callback() {
@Override
public void invoke(Object... args) {
HTDrawItem drawItem = (HTDrawItem) args[0];
int drawItemIndex = (int) args[1];
configManager.shouldReloadDrawItemIndex = drawItemIndex;
WritableMap map = Arguments.createMap();
if (drawItem != null) {
int drawColor = drawItem.drawColor;
int alpha = (drawColor >> 24) & 0xFF;
int red = (drawColor >> 16) & 0xFF;
int green = (drawColor >> 8) & 0xFF;
int blue = (drawColor) & 0xFF;
WritableArray colorList = Arguments.createArray();
colorList.pushDouble(red / 255.0);
colorList.pushDouble(green / 255.0);
colorList.pushDouble(blue / 255.0);
colorList.pushDouble(alpha / 255.0);
map.putArray("drawColor", colorList);
map.putDouble("drawLineHeight", drawItem.drawLineHeight);
map.putDouble("drawDashWidth", drawItem.drawDashWidth);
map.putDouble("drawDashSpace", drawItem.drawDashSpace);
map.putBoolean("drawIsLock", drawItem.drawIsLock);
}
map.putInt("shouldReloadDrawItemIndex", drawItemIndex);
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
id,
RNKLineView.onDrawItemDidTouchKey,
map
);
}
};
configManager.onScrollLeft = new Callback() {
@Override
public void invoke(Object... args) {
long timestamp = (long) args[0];
WritableMap map = Arguments.createMap();
map.putDouble("timestamp", timestamp);
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
id,
RNKLineView.onScrollLeftKey,
map
);
}
};
configManager.onChartTouch = new Callback() {
@Override
public void invoke(Object... args) {
float x = (float) args[0];
float y = (float) args[1];
boolean isOnClosePriceLabel = (boolean) args[2];
// If touched on close price label, trigger smooth scroll to end
if (isOnClosePriceLabel) {
klineView.smoothScrollToEnd();
}
WritableMap map = Arguments.createMap();
map.putDouble("x", x);
map.putDouble("y", y);
map.putBoolean("isOnClosePriceLabel", isOnClosePriceLabel);
// Add close price frame for debugging
WritableMap closePriceFrame = Arguments.createMap();
closePriceFrame.putDouble("x", klineView.getClosePriceLabelFrameLeft());
closePriceFrame.putDouble("y", klineView.getClosePriceLabelFrameTop());
closePriceFrame.putDouble("width", klineView.getClosePriceLabelFrameWidth());
closePriceFrame.putDouble("height", klineView.getClosePriceLabelFrameHeight());
map.putMap("closePriceFrame", closePriceFrame);
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
id,
RNKLineView.onChartTouchKey,
map
);
}
};
configManager.onDrawItemComplete = new Callback() {
@Override
public void invoke(Object... args) {
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
id,
RNKLineView.onDrawItemCompleteKey,
Arguments.createMap()
);
}
};
configManager.onDrawPointComplete = new Callback() {
@Override
public void invoke(Object... args) {
HTDrawItem drawItem = (HTDrawItem) args[0];
WritableMap map = Arguments.createMap();
map.putInt("pointCount", drawItem.pointList.size());
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
id,
RNKLineView.onDrawPointCompleteKey,
map
);
}
};
int reloadIndex = configManager.shouldReloadDrawItemIndex;
if (reloadIndex >= 0 && reloadIndex < klineView.drawContext.drawItemList.size()) {
HTDrawItem drawItem = klineView.drawContext.drawItemList.get(reloadIndex);
drawItem.drawColor = configManager.drawColor;
drawItem.drawLineHeight = configManager.drawLineHeight;
drawItem.drawDashWidth = configManager.drawDashWidth;
drawItem.drawDashSpace = configManager.drawDashSpace;
drawItem.drawIsLock = configManager.drawIsLock;
if (configManager.drawShouldTrash) {
configManager.shouldReloadDrawItemIndex = HTDrawState.showPencil;
klineView.drawContext.drawItemList.remove(reloadIndex);
configManager.drawShouldTrash = false;
}
klineView.drawContext.invalidate();
}
if (configManager.shouldFixDraw) {
configManager.shouldFixDraw = false;
klineView.drawContext.fixDrawItemList();
}
if (configManager.shouldClearDraw) {
configManager.shouldReloadDrawItemIndex = HTDrawState.none;
configManager.shouldClearDraw = false;
klineView.drawContext.clearDrawItemList();
}
}
private HTPoint convertLocation(HTPoint location) {
HTPoint reloadLocation = new HTPoint(location.x, location.y);
reloadLocation.x = Math.max(0, Math.min(reloadLocation.x, getWidth()));
reloadLocation.y = Math.max(0, Math.min(reloadLocation.y, getHeight()));
// reloadLocation.x += klineView.getScrollOffset();
reloadLocation = klineView.valuePointFromViewPoint(reloadLocation);
return reloadLocation;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
int reloadIndex = configManager.shouldReloadDrawItemIndex;
switch (reloadIndex) {
case HTDrawState.none: {
return false;
}
case HTDrawState.showPencil: {
if (configManager.drawType == HTDrawType.none) {
HTPoint location = new HTPoint(event.getX(), event.getY());
location = convertLocation(location);
if ((HTDrawItem.canResponseLocation(klineView.drawContext.drawItemList, location, klineView)) == null) {
return false;
}
}
}
}
return true;
}
private HTPoint lastLocation;
@Override
public boolean onTouchEvent(MotionEvent event) {
handlerDraw(event);
handlerShot(event);
return true;
}
private void handlerDraw(MotionEvent event) {
HTPoint location = new HTPoint(event.getX(), event.getY());
location = convertLocation(location);
HTPoint previousLocation = lastLocation != null ? lastLocation : location;
lastLocation = location;
int state = event.getAction();
Boolean isCancel = state == MotionEvent.ACTION_CANCEL;
if (isCancel) {
state = MotionEvent.ACTION_UP;
}
HTPoint translation = new HTPoint(
location.x - previousLocation.x,
location.y - previousLocation.y
);
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
lastLocation = null;
}
klineView.drawContext.touchesGesture(location, translation, state);
}
private void handlerShot(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
shotView.setPoint(null);
lastLocation = null;
} else {
shotView.setPoint(new HTPoint(event.getX(), event.getY()));
}
}
public void updateLastCandlestick(Map<String, Object> candlestickData) {
android.util.Log.d("HTKLineContainerView", "updateLastCandlestick called with data: " + candlestickData);
if (klineView == null || configManager.modelArray == null ||
configManager.modelArray.isEmpty()) {
android.util.Log.w("HTKLineContainerView", "updateLastCandlestick: Null check failed");
return;
}
// Test 2: Don't touch the view at all, just log
android.util.Log.d("HTKLineContainerView", "Test 2: No view operations, just updating data");
try {
// Get the existing last candlestick to preserve indicator data
int lastIndex = configManager.modelArray.size() - 1;
if (lastIndex < 0) {
android.util.Log.w("HTKLineContainerView", "No items in modelArray");
return;
}
KLineEntity existingEntity = configManager.modelArray.get(lastIndex);
if (existingEntity == null) {
android.util.Log.w("HTKLineContainerView", "Existing entity is null");
return;
}
// Create a new entity but preserve indicator lists from the existing entity
KLineEntity newEntity = configManager.packModel(candlestickData);
android.util.Log.d("HTKLineContainerView", "Created new entity: Close=" + newEntity.Close + ", Volume=" + newEntity.Volume);
android.util.Log.d("HTKLineContainerView", "Input candlestick data vol field: " + candlestickData.get("vol"));
// Validate the new entity
if (Float.isNaN(newEntity.Close) || Float.isInfinite(newEntity.Close)) {
android.util.Log.w("HTKLineContainerView", "Invalid close price, skipping update");
return;
}
// Only preserve indicator lists if the new data doesn't contain them
android.util.Log.d("HTKLineContainerView", "Using new indicator data from React Native");
if (newEntity.maList.isEmpty()) {
newEntity.maList = existingEntity.maList;
}
if (newEntity.maVolumeList.isEmpty()) {
newEntity.maVolumeList = existingEntity.maVolumeList;
}
if (newEntity.rsiList.isEmpty()) {
newEntity.rsiList = existingEntity.rsiList;
}
if (newEntity.wrList.isEmpty()) {
newEntity.wrList = existingEntity.wrList;
}
if (newEntity.selectedItemList.isEmpty()) {
newEntity.selectedItemList = existingEntity.selectedItemList;
}
android.util.Log.d("HTKLineContainerView", "New maVolumeList size: " + newEntity.maVolumeList.size());
if (!newEntity.maVolumeList.isEmpty()) {
android.util.Log.d("HTKLineContainerView", "Volume MA5: " + ((HTKLineTargetItem)newEntity.maVolumeList.get(0)).value +
", MA10: " + ((HTKLineTargetItem)newEntity.maVolumeList.get(1)).value);
}
// Update the last item in the data list with synchronization
synchronized (configManager.modelArray) {
if (lastIndex >= configManager.modelArray.size()) {
android.util.Log.w("HTKLineContainerView", "Index out of bounds: " + lastIndex);
return;
}
configManager.modelArray.set(lastIndex, newEntity);
android.util.Log.d("HTKLineContainerView", "Updated last candlestick at index: " + lastIndex);
}
android.util.Log.d("HTKLineContainerView", "Data update completed, now triggering safe redraw");
// Use postDelayed to ensure the data update is fully complete before triggering redraw
postDelayed(new Runnable() {
@Override
public void run() {
try {
// Call notifyChanged to properly recalculate the chart state
android.util.Log.d("HTKLineContainerView", "Calling notifyChanged to recalculate chart state");
klineView.notifyChanged();
android.util.Log.d("HTKLineContainerView", "notifyChanged completed successfully");
// Force immediate invalidation to ensure visual update
android.util.Log.d("HTKLineContainerView", "Forcing view invalidation for immediate redraw");
klineView.invalidate();
android.util.Log.d("HTKLineContainerView", "View invalidation completed");
} catch (Exception e) {
android.util.Log.e("HTKLineContainerView", "Error in redraw operations", e);
}
}
}, 50); // 50ms delay to ensure data is stable
} catch (Exception e) {
android.util.Log.e("HTKLineContainerView", "Error updating data", e);
}
}
public void addCandlesticksAtTheEnd(ReadableArray candlesticksArray) {
android.util.Log.d("HTKLineContainerView", "addCandlesticksAtTheEnd called with " + candlesticksArray.size() + " candlesticks");
if (klineView == null || configManager.modelArray == null) {
android.util.Log.w("HTKLineContainerView", "addCandlesticksAtTheEnd: Null check failed");
return;
}
if (candlesticksArray.size() == 0) {
android.util.Log.w("HTKLineContainerView", "addCandlesticksAtTheEnd: Empty candlesticks array");
return;
}
try {
// Check if user is currently at the end of the chart
boolean wasAtEnd = klineView.getScrollOffset() >= klineView.getMaxScrollX() - 10;
// Get existing model for preserving indicator lists structure
KLineEntity templateEntity = null;
if (!configManager.modelArray.isEmpty()) {
templateEntity = configManager.modelArray.get(configManager.modelArray.size() - 1);
}
// Convert ReadableArray to List of KLineEntity
List<KLineEntity> newEntities = new ArrayList<>();
for (int i = 0; i < candlesticksArray.size(); i++) {
ReadableMap candlestickMap = candlesticksArray.getMap(i);
if (candlestickMap != null) {
Map<String, Object> candlestickData = candlestickMap.toHashMap();
KLineEntity entity = configManager.packModel(candlestickData);
// Validate the entity
if (!Float.isNaN(entity.Close) && !Float.isInfinite(entity.Close)) {
// The indicator lists are now properly populated by packModel() from React Native data
// No need for manual calculation since the data already includes calculated indicators
android.util.Log.d("HTKLineContainerView", "Using indicator data from React Native - maList.size=" + entity.maList.size() + ", maVolumeList.size=" + entity.maVolumeList.size());
newEntities.add(entity);
} else {
android.util.Log.w("HTKLineContainerView", "Skipping invalid candlestick at index " + i);
}
}
}
if (newEntities.isEmpty()) {
android.util.Log.w("HTKLineContainerView", "No valid candlesticks to add");
return;
}
// Add new entities to the end of the array with synchronization
synchronized (configManager.modelArray) {
configManager.modelArray.addAll(newEntities);
android.util.Log.d("HTKLineContainerView", "Added " + newEntities.size() + " new candlesticks to the end");
android.util.Log.d("HTKLineContainerView", "Total candlesticks now: " + configManager.modelArray.size());
android.util.Log.d("HTKLineContainerView", "Was at end before adding: " + wasAtEnd);
}
// Trigger redraw and optionally scroll to end
postDelayed(new Runnable() {
@Override
public void run() {
try {
android.util.Log.d("HTKLineContainerView", "Calling notifyChanged after adding candlesticks");
klineView.notifyChanged();
android.util.Log.d("HTKLineContainerView", "Forcing view invalidation after adding candlesticks");
klineView.invalidate();
// If user was at the end, keep them at the end
if (wasAtEnd) {
postDelayed(new Runnable() {
@Override
public void run() {
android.util.Log.d("HTKLineContainerView", "Scrolling to end after adding new data");
klineView.setScrollX(klineView.getMaxScrollX());
}
}, 100); // Additional delay for scroll
}
} catch (Exception e) {
android.util.Log.e("HTKLineContainerView", "Error in redraw operations after adding candlesticks", e);
}
}
}, 50); // 50ms delay to ensure data is stable
} catch (Exception e) {
android.util.Log.e("HTKLineContainerView", "Error adding candlesticks", e);
}
}
public void addCandlesticksAtTheStart(ReadableArray candlesticksArray) {
android.util.Log.d("HTKLineContainerView", "addCandlesticksAtTheStart called with " + candlesticksArray.size() + " candlesticks");
if (klineView == null || configManager.modelArray == null) {
android.util.Log.w("HTKLineContainerView", "addCandlesticksAtTheStart: Null check failed");
return;
}
if (candlesticksArray.size() == 0) {
android.util.Log.w("HTKLineContainerView", "addCandlesticksAtTheStart: Empty candlesticks array");
return;
}
try {
// Reset the scroll left trigger flag to allow new triggers
klineView.resetScrollLeftTrigger();
// Convert ReadableArray to List of KLineEntity
List<KLineEntity> newEntities = new ArrayList<>();
for (int i = 0; i < candlesticksArray.size(); i++) {
ReadableMap candlestickMap = candlesticksArray.getMap(i);
if (candlestickMap != null) {
Map<String, Object> candlestickData = candlestickMap.toHashMap();
KLineEntity entity = configManager.packModel(candlestickData);
// Validate the entity
if (!Float.isNaN(entity.Close) && !Float.isInfinite(entity.Close)) {
// The indicator lists are now properly populated by packModel() from React Native data
android.util.Log.d("HTKLineContainerView", "Using indicator data from React Native - maList.size=" + entity.maList.size() + ", maVolumeList.size=" + entity.maVolumeList.size());
newEntities.add(entity);
} else {
android.util.Log.w("HTKLineContainerView", "Skipping invalid candlestick at index " + i);
}
}
}
if (newEntities.isEmpty()) {
android.util.Log.w("HTKLineContainerView", "No valid candlesticks to add");
return;
}
// Get current scroll position before modifying data
int currentScrollX = klineView.getScrollOffset();
// Add new entities to the beginning of the array (prepend)
synchronized (configManager.modelArray) {
configManager.modelArray.addAll(0, newEntities);
android.util.Log.d("HTKLineContainerView", "Added " + newEntities.size() + " new candlesticks to the start");
android.util.Log.d("HTKLineContainerView", "Total candlesticks now: " + configManager.modelArray.size());
}
// Set up scroll position adjustment using the config manager mechanism
int addedWidth = newEntities.size() * (int) klineView.configManager.itemWidth;
configManager.scrollPositionAdjustment = addedWidth;
configManager.shouldAdjustScrollPosition = true;
android.util.Log.d("HTKLineContainerView", "Set scroll position adjustment: " + addedWidth + " pixels");
// Use the same reload mechanism as optionList
int previousScrollX = klineView.getScrollOffset();
klineView.notifyChanged();
if (klineView.configManager.shouldAdjustScrollPosition) {
// Adjust scroll position to compensate for the new data added at start
int newScrollX = previousScrollX + klineView.configManager.scrollPositionAdjustment;
android.util.Log.d("HTKLineContainerView", "Adjusting scroll position from " + previousScrollX + " to " + newScrollX);
klineView.setScrollX(newScrollX);
// Reset the flags
configManager.shouldAdjustScrollPosition = false;
configManager.scrollPositionAdjustment = 0;
}
} catch (Exception e) {
android.util.Log.e("HTKLineContainerView", "Error adding candlesticks at start", e);
}
}
}