-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSyntaxView.java
More file actions
628 lines (530 loc) · 19.1 KB
/
SyntaxView.java
File metadata and controls
628 lines (530 loc) · 19.1 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
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
package ir.ninjacoder.codesnap.widget;
import android.animation.*;
import android.animation.AnimatorListenerAdapter;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ClipData;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.InputType;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
import android.text.Spannable;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.tooltip.TooltipDrawable;
import ir.ninjacoder.codesnap.R;
import ir.ninjacoder.codesnap.Utils.ObjectUtils;
import ir.ninjacoder.codesnap.Utils.IncrementalHighlighter;
import ir.ninjacoder.codesnap.LangType;
import ir.ninjacoder.codesnap.Utils.Highlighter;
import ir.ninjacoder.codesnap.Utils.CodeImpl;
import ir.ninjacoder.codesnap.colorhelper.ColorHelper;
import ir.ninjacoder.codesnap.folding.CodeFoldingManager;
import ir.ninjacoder.codesnap.markdownpreview.MarkDownTextHelper;
public class SyntaxView extends ScrollView {
private CodeEditText code;
private boolean autoIndent = false;
private LineNumberCalculator lineCode;
private ColorHelper color = new ColorHelper();
private CodeFoldingManager foldingManager;
private boolean codeFoldingEnabled = true;
private TextView tv;
private String oldText = "";
private TextWatcher textWatcher;
private IncrementalHighlighter incrementalHighlighter;
private boolean isMarkdownMode = false;
private TooltipDrawable tooltip;
private boolean isTooltipShowing = false;
private int originalStart = -1;
private int originalEnd = -1;
private String originalText = "";
public SyntaxView(Context context) {
super(context);
initialize(context);
}
public SyntaxView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
private void initialize(Context context) {
inflate(context, R.layout.syntaxview, this);
code = findViewById(R.id.code);
tv = findViewById(R.id.mark);
lineCode = new LineNumberCalculator(code.getText().toString());
foldingManager = new CodeFoldingManager(color);
code.setTextSize(14);
code.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
code.setSingleLine(false);
code.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
code.setBackgroundColor(Color.TRANSPARENT);
setHorizontalScrollBarEnabled(true);
code.setSelection(code.getText().length());
code.setLineNumberColor(color.getLinenumbercolor());
applyTheme();
updateLineNumbers();
code.setOnLongClickListener(
v -> {
int start = code.getSelectionStart();
int end = code.getSelectionEnd();
if (start != end) {
String selectedText = code.getText().toString().substring(start, end);
originalStart = start;
originalEnd = end;
originalText = selectedText;
ClipData data = ClipData.newPlainText("text", selectedText);
View.DragShadowBuilder shadow = new CustomDragShadowBuilder(code, start, end);
v.startDragAndDrop(data, shadow, null, View.DRAG_FLAG_OPAQUE);
return true;
}
return false;
});
code.setOnDragListener(
new View.OnDragListener() {
private ValueAnimator cursorAnimator;
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
animateCursorAlpha(0.3f, 1.0f, 200);
return true;
case DragEvent.ACTION_DRAG_ENTERED:
animateBackgroundColor(0x1067C8F5, 300);
return true;
case DragEvent.ACTION_DRAG_LOCATION:
int pos = code.getOffsetForPosition(event.getX(), event.getY());
animateCursorPosition(pos);
return true;
case DragEvent.ACTION_DRAG_EXITED:
animateBackgroundColor(Color.TRANSPARENT, 200);
return true;
case DragEvent.ACTION_DROP:
ClipData.Item item = event.getClipData().getItemAt(0);
String draggedText = item.getText().toString();
animateBackgroundColor(0x3067C8F5, 150);
int dropPos = code.getSelectionStart();
code.getText().insert(dropPos, draggedText);
animateCursorAlpha(1.0f, 0.3f, 100);
animateCursorAlpha(0.3f, 1.0f, 100);
originalStart = -1;
originalEnd = -1;
originalText = "";
return true;
case DragEvent.ACTION_DRAG_ENDED:
if (originalStart != -1 && originalEnd != -1) {
code.getText().insert(originalStart, originalText);
code.setSelection(originalStart + originalText.length());
}
animateBackgroundColor(Color.TRANSPARENT, 300);
animateCursorAlpha(code.getAlpha(), 1.0f, 200);
originalStart = -1;
originalEnd = -1;
originalText = "";
return true;
}
return true;
}
private void animateBackgroundColor(int targetColor, int duration) {
ValueAnimator colorAnimator =
ValueAnimator.ofObject(
new ArgbEvaluator(), ((TextView) code).getHighlightColor(), targetColor);
colorAnimator.setDuration(duration);
colorAnimator.addUpdateListener(
animator -> {
((TextView) code).setHighlightColor((int) animator.getAnimatedValue());
});
colorAnimator.start();
}
private void animateCursorAlpha(float from, float to, int duration) {
if (cursorAnimator != null && cursorAnimator.isRunning()) {
cursorAnimator.cancel();
}
cursorAnimator = ValueAnimator.ofFloat(from, to);
cursorAnimator.setDuration(duration);
cursorAnimator.addUpdateListener(
animator -> {
float alpha = (float) animator.getAnimatedValue();
code.setAlpha(alpha);
});
cursorAnimator.start();
}
private void animateCursorPosition(int newPos) {
AnimatorSet set = new AnimatorSet();
ObjectAnimator cursorAnim = ObjectAnimator.ofInt(code, "selectionStart", newPos);
ObjectAnimator cursorAnim2 = ObjectAnimator.ofInt(code, "selectionEnd", newPos);
set.playTogether(cursorAnim, cursorAnim2);
set.setDuration(50);
set.start();
}
});
textWatcher =
new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
oldText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int numLines = code.getLineCount();
StringBuilder linesText = new StringBuilder();
for (int i = 1; i <= numLines; i++) {
linesText.append(i).append("\n");
}
if (codeFoldingEnabled) {
foldingManager.detectFoldingRegions(s.toString());
}
}
@Override
public void afterTextChanged(Editable s) {
if (autoIndent) {
char lastDiff = getLastDifference(s.toString(), oldText);
if (lastDiff == '{' || lastDiff == ':') {
int pos = code.getSelectionStart();
code.getText().insert(pos, "\n ");
code.setSelection(pos + 2);
}
}
code.invalidate();
}
};
// code.addTextChangedListener(textWatcher);
}
public void setLangType(LangType langType) {
Highlighter highlighter = new CodeImpl();
incrementalHighlighter = new IncrementalHighlighter(highlighter, langType, color);
incrementalHighlighter.attach(code.getText());
}
private char getLastDifference(String a, String b) {
if (a.equals(b)) return '.';
int len = Math.min(a.length(), b.length());
for (int i = 0; i < len; i++) {
if (a.charAt(i) != b.charAt(i)) return a.charAt(i);
}
return a.length() > b.length() ? a.charAt(a.length() - 1) : '.';
}
public void toggleFoldingAtLine(int line) {
if (codeFoldingEnabled && foldingManager != null) {
CodeFoldingManager.FoldingRegion region = foldingManager.findFoldingRegionAtLine(line);
if (region != null) {
foldingManager.toggleFolding(region);
updateDisplayWithFolding();
postInvalidate();
code.invalidate();
}
}
}
private void updateDisplayWithFolding() {
String originalText = code.getText().toString();
int selection = code.getSelectionStart();
code.removeTextChangedListener(textWatcher);
foldingManager.detectFoldingRegions(originalText);
SpannableStringBuilder foldedText = foldingManager.applyFolding(originalText);
// حفظ هایلایتها و استایلها
Editable currentText = code.getText();
Object[] spans = currentText.getSpans(0, currentText.length(), Object.class);
code.setText(foldedText);
// بازگردانی هایلایتها
Editable newText = code.getText();
for (Object span : spans) {
if (span instanceof BackgroundColorSpan || span instanceof StyleSpan) {
int start = currentText.getSpanStart(span);
int end = currentText.getSpanEnd(span);
if (start >= 0 && end <= newText.length()) {
newText.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
int newSelection = calculateNewCursorPosition(originalText, foldedText.toString(), selection);
if (newSelection >= 0 && newSelection <= foldedText.length()) {
code.setSelection(newSelection);
}
code.addTextChangedListener(textWatcher);
}
private int calculateNewCursorPosition(String originalText, String foldedText, int originalPos) {
if (originalText.equals(foldedText)) {
return originalPos;
}
if (originalPos >= foldedText.length()) {
return foldedText.length();
}
String[] originalLines = originalText.split("\n", -1);
int originalLine = 0;
int currentPos = 0;
for (int i = 0; i < originalLines.length; i++) {
currentPos += originalLines[i].length();
if (currentPos >= originalPos) {
originalLine = i;
break;
}
currentPos++;
}
String[] foldedLines = foldedText.split("\n", -1);
if (originalLine < foldedLines.length) {
int newPos = 0;
for (int i = 0; i < originalLine; i++) {
newPos += foldedLines[i].length() + 1;
}
String originalLineText = originalLines[originalLine];
String foldedLineText = foldedLines[originalLine];
int lineStartPos = 0;
for (int i = 0; i < originalLine; i++) {
lineStartPos += originalLines[i].length() + 1;
}
int offsetInLine = originalPos - lineStartPos;
offsetInLine = Math.min(offsetInLine, foldedLineText.length());
return newPos + offsetInLine;
}
return foldedText.length();
}
public void setCodeFoldingEnabled(boolean enabled) {
this.codeFoldingEnabled = enabled;
code.setCodeFoldingEnabled(enabled);
}
public void setAutoIndent(boolean val) {
this.autoIndent = val;
}
public void showLineNumber(boolean show) {
if (show) {
code.setShowLineNumbers(show);
code.setAlpha(0f);
code.setScaleX(0.8f);
code.setScaleY(0.8f);
code.animate()
.alpha(1f)
.scaleX(1f)
.scaleY(1f)
.setDuration(350)
.setInterpolator(new OvershootInterpolator(1.0f))
.setListener(null);
} else {
code.animate()
.alpha(0f)
.scaleX(0.8f)
.scaleY(0.8f)
.setDuration(250)
.setInterpolator(new AccelerateInterpolator())
.setListener(
new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
code.setShowLineNumbers(show);
code.setAlpha(1f);
code.setScaleX(1f);
code.setScaleY(1f);
}
});
}
updateLineNumbers();
}
public void setFont(Typeface tf) {
code.setTypeface(tf);
}
public void setTypeFaceEditor(Typeface f) {
code.setTypeface(f);
}
public void setTypeFaceLineNumber(Typeface d) {
code.setLineNumberTypeFace(d);
}
public void setText(String text) {
code.removeTextChangedListener(textWatcher);
code.setText(text);
updateLineNumbers();
code.addTextChangedListener(textWatcher);
}
public String getText() {
return code.getText().toString();
}
public void setTextSize(float size) {
code.setTextSize(size);
}
public void setTextColor(int color) {
code.setTextColor(color);
}
void setLineNumberBackgroundColor(int color) {}
void setCodeBackgroundColor(int color) {
code.setBackgroundColor(color);
}
public void setPadding(int left, int top, int right, int bottom) {
code.setPadding(left, top, right, bottom);
}
public void setLineNumberPadding(int left, int top, int right, int bottom) {}
public void setHint(String hint) {
code.setHint(hint);
}
public void setHintTextColor(int color) {
code.setHintTextColor(color);
}
public void setSelection(int index) {
code.setSelection(index);
}
public CodeEditText getCode() {
return code;
}
public int getLine() {
return lineCode.getLine();
}
public int getColumn() {
return lineCode.getColumn();
}
public int getStart() {
return lineCode.findLineStart();
}
public int getEnd() {
return lineCode.findLineEnd();
}
public void applyTheme() {
setCodeBackgroundColor(Color.TRANSPARENT);
setTextColor(color.getTextnormal());
invalidate();
}
public void setColorHelper(ColorHelper colorHelper) {
this.color = colorHelper;
applyTheme();
}
private void updateLineNumbers() {
String text = code.getText().toString();
int numLines = text.isEmpty() ? 1 : countLines(text);
StringBuilder linesText = new StringBuilder();
for (int i = 1; i <= numLines; i++) {
linesText.append(i).append("\n");
}
}
private int countLines(String text) {
int count = 1;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '\n') {
count++;
}
}
return count;
}
public void showMarkDownView(boolean showMarkdown) {
if (showMarkdown) {
// Switch to Markdown view
if (code.getVisibility() == VISIBLE) {
// Animate code view out
code.animate()
.scaleX(0.7f)
.scaleY(0.7f)
.alpha(0f)
.setDuration(300)
.setInterpolator(new AccelerateInterpolator())
.withEndAction(
() -> {
code.setVisibility(GONE);
code.setScaleX(1f);
code.setScaleY(1f);
code.setAlpha(1f);
// Show markdown view after code view hides
tv.setVisibility(VISIBLE);
tv.setScaleX(0.5f);
tv.setScaleY(0.5f);
tv.setAlpha(0f);
MarkDownTextHelper.handleMarkDown(tv, code.getText().toString());
tv.animate()
.scaleX(1f)
.scaleY(1f)
.alpha(1f)
.setDuration(400)
.setInterpolator(new OvershootInterpolator(0.8f))
.start();
})
.start();
}
isMarkdownMode = true;
} else {
// Switch to code view
if (tv.getVisibility() == VISIBLE) {
// Animate markdown view out
tv.animate()
.scaleX(0.7f)
.scaleY(0.7f)
.alpha(0f)
.setDuration(300)
.setInterpolator(new AccelerateInterpolator())
.withEndAction(
() -> {
tv.setVisibility(GONE);
tv.setScaleX(1f);
tv.setScaleY(1f);
tv.setAlpha(1f);
// Show code view after markdown view hides
code.setVisibility(VISIBLE);
code.setScaleX(0.5f);
code.setScaleY(0.5f);
code.setAlpha(0f);
code.animate()
.scaleX(1f)
.scaleY(1f)
.alpha(1f)
.setDuration(400)
.setInterpolator(new OvershootInterpolator(0.8f))
.start();
})
.start();
}
isMarkdownMode = false;
}
invalidate();
requestLayout();
}
public void toggleMarkdownView() {
showMarkDownView(!isMarkdownMode);
}
public boolean getisMarkdownMode() {
return this.isMarkdownMode;
}
private static class CustomDragShadowBuilder extends View.DragShadowBuilder {
private final Paint paint;
private final Paint bgPaint;
private final Rect bounds;
private final String selectedText;
public CustomDragShadowBuilder(View view, int start, int end) {
super(view);
TextView textView = (TextView) view;
this.selectedText = textView.getText().subSequence(start, end).toString();
float textSize = textView.getTextSize();
paint = new Paint();
paint.setTextSize(textSize);
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
bgPaint = new Paint();
bgPaint.setColor(0xCC2196F3);
bgPaint.setAntiAlias(true);
bgPaint.setStyle(Paint.Style.FILL);
bounds = new Rect();
paint.getTextBounds(selectedText, 0, selectedText.length(), bounds);
}
@Override
public void onDrawShadow(Canvas canvas) {
RectF rect = new RectF(0, 0, bounds.width() + 32, bounds.height() + 24);
canvas.drawRoundRect(rect, 16, 16, bgPaint);
canvas.drawText(selectedText, 16, bounds.height() + 8, paint);
}
@Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
shadowSize.set(bounds.width() + 48, bounds.height() + 32);
shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
}
}
}