file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
PageAdapter.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/editor/adapter/PageAdapter.java
package com.tyron.code.ui.editor.adapter; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.lifecycle.Lifecycle; import androidx.recyclerview.widget.DiffUtil; import androidx.viewpager2.adapter.FragmentStateAdapter; import com.tyron.fileeditor.api.FileEditor; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class PageAdapter extends FragmentStateAdapter { private final List<FileEditor> data = new ArrayList<>(); public PageAdapter(FragmentManager fm, Lifecycle lifecycle) { super(fm, lifecycle); } public void submitList(List<FileEditor> files) { DiffUtil.DiffResult result = DiffUtil.calculateDiff( new DiffUtil.Callback() { @Override public int getOldListSize() { return data.size(); } @Override public int getNewListSize() { return files.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return Objects.equals(data.get(oldItemPosition), files.get(newItemPosition)); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return Objects.equals(data.get(oldItemPosition), files.get(newItemPosition)); } }); data.clear(); data.addAll(files); result.dispatchUpdatesTo(this); } @Override public int getItemCount() { return data.size(); } @Override public long getItemId(int position) { if (data.isEmpty()) { return -1; } return data.get(position).hashCode(); } @Override public boolean containsItem(long itemId) { for (FileEditor d : data) { if (d.hashCode() == itemId) { return true; } } return false; } @NonNull @Override public Fragment createFragment(int p1) { return data.get(p1).getFragment(); } }
2,097
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompiledEditorScheme.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/editor/scheme/CompiledEditorScheme.java
package com.tyron.code.ui.editor.scheme; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.util.TypedValue; import androidx.annotation.StyleableRes; import com.google.android.material.color.MaterialColors; import com.google.common.collect.ImmutableMap; import io.github.rosemoe.sora.widget.schemes.EditorColorScheme; import java.util.Map; import org.codeassist.unofficial.R; /** An editor color scheme that is based on compiled xml files. */ public class CompiledEditorScheme extends EditorColorScheme { private static final Map<Integer, Integer> sResIdMap = ImmutableMap.<Integer, Integer>builder() .put(R.styleable.EditorColorScheme_keyword, KEYWORD) .put(R.styleable.EditorColorScheme_operator, OPERATOR) .put(R.styleable.EditorColorScheme_annotation, ANNOTATION) .put(R.styleable.EditorColorScheme_xmlAttributeName, ATTRIBUTE_NAME) .put(R.styleable.EditorColorScheme_xmlAttributeValue, ATTRIBUTE_VALUE) .put(R.styleable.EditorColorScheme_comment, COMMENT) .put(R.styleable.EditorColorScheme_htmlTag, HTML_TAG) .put(R.styleable.EditorColorScheme_identifierName, IDENTIFIER_NAME) .put(R.styleable.EditorColorScheme_identifierVar, IDENTIFIER_VAR) .put(R.styleable.EditorColorScheme_functionName, FUNCTION_NAME) .put(R.styleable.EditorColorScheme_literal, LITERAL) .put(R.styleable.EditorColorScheme_textNormal, TEXT_NORMAL) .put(R.styleable.EditorColorScheme_blockLineColor, BLOCK_LINE) .put(R.styleable.EditorColorScheme_problemError, PROBLEM_ERROR) .put(R.styleable.EditorColorScheme_problemWarning, PROBLEM_WARNING) .put(R.styleable.EditorColorScheme_problemTypo, PROBLEM_TYPO) .put(R.styleable.EditorColorScheme_selectedTextBackground, SELECTED_TEXT_BACKGROUND) .put(R.styleable.EditorColorScheme_completionPanelBackground, AUTO_COMP_PANEL_BG) .put(R.styleable.EditorColorScheme_completionPanelStrokeColor, AUTO_COMP_PANEL_CORNER) .put(R.styleable.EditorColorScheme_lineNumberBackground, LINE_NUMBER_BACKGROUND) .put(R.styleable.EditorColorScheme_lineNumberTextColor, LINE_NUMBER_PANEL_TEXT) .put(R.styleable.EditorColorScheme_lineNumberDividerColor, LINE_DIVIDER) .put(R.styleable.EditorColorScheme_wholeBackground, WHOLE_BACKGROUND) .build(); public CompiledEditorScheme(Context context) { Resources.Theme theme = context.getTheme(); TypedValue value = new TypedValue(); theme.resolveAttribute(R.attr.editorColorScheme, value, true); TypedArray typedArray = context.obtainStyledAttributes(value.data, R.styleable.EditorColorScheme); for (Integer resId : sResIdMap.keySet()) { putColor(context, resId, typedArray); } typedArray.recycle(); } private void putColor(Context context, @StyleableRes int res, TypedArray array) { if (!array.hasValue(res)) { return; } Integer integer = sResIdMap.get(res); if (integer == null) { return; } if (array.getType(res) == TypedValue.TYPE_ATTRIBUTE) { TypedValue typedValue = new TypedValue(); array.getValue(res, typedValue); int color = MaterialColors.getColor(context, typedValue.data, -1); setColorInternal(integer, color); return; } setColorInternal(integer, array.getColor(res, 0)); } private void setColorInternal(int id, int value) { mColors.put(id, value); } }
3,573
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CodeAssistColorScheme.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/editor/scheme/CodeAssistColorScheme.java
package com.tyron.code.ui.editor.scheme; import android.graphics.Color; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.WorkerThread; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import io.github.rosemoe.sora.widget.schemes.EditorColorScheme; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; /** An editor color scheme that can be serialized and deserialized as json */ @Keep public class CodeAssistColorScheme extends EditorColorScheme { @WorkerThread public static CodeAssistColorScheme fromFile(@NonNull File file) throws IOException { String contents = FileUtils.readFileToString(file, StandardCharsets.UTF_8); CodeAssistColorScheme scheme = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .setPrettyPrinting() .create() .fromJson(contents, CodeAssistColorScheme.class); if (scheme == null) { throw new IOException("Unable to parse scheme file."); } if (scheme.mName == null) { throw new IOException("Scheme does not contain a name."); } if (scheme.mColors == null) { throw new IOException("Scheme does not have colors."); } return scheme; } @Expose @SerializedName("name") private String mName; @Expose @SerializedName("colors") private Map<String, String> mNameToColorMap; public CodeAssistColorScheme() { for (Integer id : Keys.sIdToNameMap.keySet()) { int color = getColor(id); setColor(id, color); } } /** * Return the key of the id that will be serialized. * * @param id The editor color scheme id * @return the mapped key */ protected String getName(int id) { return Keys.sIdToNameMap.get(id); } @Override public void setColor(int type, int color) { super.setColor(type, color); if (mNameToColorMap == null) { mNameToColorMap = new HashMap<>(); } String name = getName(type); if (name != null) { mNameToColorMap.remove(name); mNameToColorMap.put(name, "#" + Integer.toHexString(color)); } } @Override public int getColor(int type) { if (mNameToColorMap == null) { mNameToColorMap = new HashMap<>(); } String name = getName(type); if (name != null) { String color = mNameToColorMap.get(name); if (color != null) { try { return Color.parseColor(color); } catch (IllegalArgumentException ignored) { // fall through } } } return super.getColor(type); } @NonNull public String toString() { return new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .setPrettyPrinting() .create() .toJson(this); } public static final class Keys { private static final BiMap<Integer, String> sIdToNameMap = HashBiMap.create(); static { sIdToNameMap.put(WHOLE_BACKGROUND, "wholeBackground"); sIdToNameMap.put(AUTO_COMP_PANEL_BG, "completionPanelBackground"); sIdToNameMap.put(AUTO_COMP_PANEL_CORNER, "completionPanelStrokeColor"); sIdToNameMap.put(LINE_NUMBER, "lineNumber"); sIdToNameMap.put(LINE_NUMBER_BACKGROUND, "lineNumberBackground"); sIdToNameMap.put(LINE_NUMBER_PANEL, "lineNumberPanel"); sIdToNameMap.put(LINE_NUMBER_PANEL_TEXT, "lineNumberPanelText"); sIdToNameMap.put(LINE_DIVIDER, "lineDivider"); sIdToNameMap.put(SELECTION_HANDLE, "selectionHandle"); sIdToNameMap.put(SELECTION_INSERT, "selectionInsert"); sIdToNameMap.put(SCROLL_BAR_TRACK, "scrollbarTrack"); sIdToNameMap.put(SCROLL_BAR_THUMB, "scrollbarThumb"); sIdToNameMap.put(SCROLL_BAR_THUMB_PRESSED, "scrollbarThumbPressed"); sIdToNameMap.put(PROBLEM_TYPO, "problemTypo"); sIdToNameMap.put(PROBLEM_ERROR, "problemError"); sIdToNameMap.put(PROBLEM_WARNING, "problemWarning"); sIdToNameMap.put(BLOCK_LINE, "blockLine"); sIdToNameMap.put(BLOCK_LINE_CURRENT, "blockLineCurrent"); sIdToNameMap.put(UNDERLINE, "underline"); sIdToNameMap.put(CURRENT_LINE, "currentLine"); sIdToNameMap.put(TEXT_NORMAL, "textNormal"); sIdToNameMap.put(SELECTED_TEXT_BACKGROUND, "selectedTextBackground"); sIdToNameMap.put(MATCHED_TEXT_BACKGROUND, "matchedTextBackground"); sIdToNameMap.put(ATTRIBUTE_NAME, "attributeName"); sIdToNameMap.put(ATTRIBUTE_VALUE, "attributeValue"); sIdToNameMap.put(HTML_TAG, "htmlTag"); sIdToNameMap.put(ANNOTATION, "annotation"); sIdToNameMap.put(FUNCTION_NAME, "functionName"); sIdToNameMap.put(IDENTIFIER_NAME, "identifierName"); sIdToNameMap.put(IDENTIFIER_VAR, "identifierVar"); sIdToNameMap.put(LITERAL, "literal"); sIdToNameMap.put(OPERATOR, "operator"); sIdToNameMap.put(COMMENT, "comment"); sIdToNameMap.put(KEYWORD, "keyword"); } } }
5,173
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AppLogFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/editor/log/AppLogFragment.java
package com.tyron.code.ui.editor.log; import static io.github.rosemoe.sora2.text.EditorUtil.getDefaultColorScheme; import android.content.ClipboardManager; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.os.Looper; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.tyron.builder.log.LogViewModel; import com.tyron.builder.model.DiagnosticWrapper; import com.tyron.builder.project.Project; import com.tyron.code.ApplicationLoader; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.editor.impl.text.rosemoe.CodeEditorFragment; import com.tyron.code.ui.editor.impl.text.rosemoe.CodeEditorView; import com.tyron.code.ui.editor.scheme.CompiledEditorScheme; import com.tyron.code.ui.main.MainViewModel; import com.tyron.code.ui.project.ProjectManager; import com.tyron.code.ui.theme.ThemeRepository; import com.tyron.code.util.ApkInstaller; import com.tyron.common.SharedPreferenceKeys; import com.tyron.editor.Caret; import com.tyron.fileeditor.api.FileEditorManager; import io.github.rosemoe.sora.langs.textmate.theme.TextMateColorScheme; import io.github.rosemoe.sora2.text.EditorUtil; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.logging.Handler; import javax.tools.Diagnostic; import org.codeassist.unofficial.R; public class AppLogFragment extends Fragment implements ProjectManager.OnProjectOpenListener { /** Only used in IDE Logs * */ private Handler mHandler; public static AppLogFragment newInstance(int id) { AppLogFragment fragment = new AppLogFragment(); Bundle bundle = new Bundle(); bundle.putInt("id", id); fragment.setArguments(bundle); return fragment; } private CodeEditorView mEditor; private FloatingActionButton copyText, actionFab; private View mRoot; private int id; private MainViewModel mMainViewModel; private LogViewModel mModel; private OnDiagnosticClickListener mListener; List<DiagnosticWrapper> diags = new ArrayList<>(); List<ErrorItem> errors = new ArrayList<>(); public AppLogFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); id = requireArguments().getInt("id"); mModel = new ViewModelProvider(requireActivity()).get(LogViewModel.class); mMainViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class); } @Override public View onCreateView( @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRoot = inflater.inflate(R.layout.app_log_fragment, container, false); return mRoot; } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mEditor = view.findViewById(R.id.output_text); copyText = view.findViewById(R.id.copy_text); actionFab = view.findViewById(R.id.action_fab); actionFab.setVisibility(View.GONE); actionFab.setOnClickListener( v -> { String output = mEditor.getText().toString().trim(); if (output != null && !output.isEmpty()) { if (output.contains("INSTALL") || output.contains("Generated APK has been saved")) { Project project = ProjectManager.getInstance().getCurrentProject(); if (project != null) { File mApkFile = new File(project.getRootFile(), "app/build/bin/signed.apk"); ApkInstaller.installApplication(requireContext(), mApkFile.getAbsolutePath()); } } else if (output.contains("ERROR") || output.contains("error") || output.contains("failed") || output.contains("Failed")) { if (errors != null) { errors.clear(); } for (DiagnosticWrapper diagnostic : diags) { if (diagnostic != null) { if (diagnostic.getKind() != null && diagnostic.getKind() == Diagnostic.Kind.ERROR) { String error = diagnostic.getMessage(Locale.getDefault()); if (diagnostic.getSource() != null) { String label = diagnostic.getSource().getName(); if (label != null) { label = label + " : line:" + diagnostic.getLineNumber() + " : " + error; errors.add(new ErrorItem(label, diagnostic.getSource(), diagnostic)); } } } } } if (errors != null && !errors.isEmpty()) { ArrayAdapter<ErrorItem> adapter = new ArrayAdapter<ErrorItem>( requireContext(), android.R.layout.select_dialog_item, android.R.id.text1, errors) { @NonNull @Override public View getView( int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView textView = view.findViewById(android.R.id.text1); ErrorItem errorItem = getItem(position); textView.setPadding(12, 12, 12, 12); textView.setTextSize(12); textView.setTextColor(0xffcf6679); textView.setText(errorItem.getMessage()); textView.setCompoundDrawablesRelativeWithIntrinsicBounds( R.drawable.ic_error, 0, 0, 0); return view; } }; MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext()); builder.setTitle(getString(R.string.errors_found, String.valueOf(errors.size()))); builder.setAdapter( adapter, (dialog, which) -> { ErrorItem selectedErrorItem = errors.get(which); if (selectedErrorItem.getFile() != null) { if (getContext() != null) { FileEditorManager manager = FileEditorManagerImpl.getInstance(); manager.openFile( requireContext(), selectedErrorItem.getFile(), it -> { if (selectedErrorItem.getDiagnosticWrapper().getLineNumber() > 0 && selectedErrorItem.getDiagnosticWrapper().getColumnNumber() > 0) { Bundle bundle = new Bundle(it.getFragment().getArguments()); bundle.putInt( CodeEditorFragment.KEY_LINE, (int) selectedErrorItem.getDiagnosticWrapper().getLineNumber()); bundle.putInt( CodeEditorFragment.KEY_COLUMN, (int) selectedErrorItem .getDiagnosticWrapper() .getColumnNumber()); it.getFragment().setArguments(bundle); manager.openFileEditor(it); } }); } } }); builder.show(); } } } }); copyText.setOnClickListener( v -> { Caret caret = mEditor.getCaret(); if (!(caret.getStartLine() == caret.getEndLine() && caret.getStartColumn() == caret.getEndColumn())) { CharSequence textToCopy = mEditor.getContent().subSequence(caret.getStart(), caret.getEnd()); String content = textToCopy.toString().trim(); if (content != null && !content.isEmpty()) { copyContent(content); } } else { String content = mEditor.getText().toString().trim(); if (content != null && !content.isEmpty()) { copyContent(content); } } }); mEditor.setEditable(false); configureEditor(mEditor); if (mModel != null) { mModel.getLogs(id).observe(getViewLifecycleOwner(), this::process); } } private void copyContent(String content) { ClipboardManager clipboard = (ClipboardManager) requireContext().getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(content); Toast toast = Toast.makeText(requireContext(), R.string.copied_to_clipboard, Toast.LENGTH_LONG); toast.show(); } private void configureEditor(@NonNull CodeEditorView editor) { editor.setEditable(false); editor.setColorScheme(new CompiledEditorScheme(requireContext())); /* String schemeValue = ApplicationLoader.getDefaultPreferences().getString(SharedPreferenceKeys.SCHEME, null); if (schemeValue != null && new File(schemeValue).exists() && ThemeRepository.getColorScheme(schemeValue) != null) { TextMateColorScheme scheme = ThemeRepository.getColorScheme(schemeValue); if (scheme != null) { editor.setColorScheme(scheme); } }*/ String key = EditorUtil.isDarkMode(requireContext()) ? ThemeRepository.DEFAULT_NIGHT : ThemeRepository.DEFAULT_LIGHT; TextMateColorScheme scheme = ThemeRepository.getColorScheme(key); if (scheme == null) { scheme = getDefaultColorScheme(requireContext()); ThemeRepository.putColorScheme(key, scheme); } mEditor.setColorScheme(scheme); // editor.setBackgroundAnalysisEnabled(false); editor.setTypefaceText( ResourcesCompat.getFont(requireContext(), R.font.jetbrains_mono_regular)); // editor.setLigatureEnabled(true); // editor.setHighlightCurrentBlock(true); editor.setEdgeEffectColor(Color.TRANSPARENT); editor.setInputType( EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS | EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); SharedPreferences pref = ApplicationLoader.getDefaultPreferences(); // editor.setWordwrap(pref.getBoolean(SharedPreferenceKeys.EDITOR_WORDWRAP, false)); editor.setWordwrap(true); editor.setTextSize(Integer.parseInt(pref.getString(SharedPreferenceKeys.FONT_SIZE, "10"))); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onDestroyView() { super.onDestroyView(); } private void process(List<DiagnosticWrapper> texts) { final android.os.Handler handler = new android.os.Handler(Looper.getMainLooper()); if (handler != null) { handler.postDelayed( () -> { SpannableStringBuilder combinedText = new SpannableStringBuilder(); if (texts != null) { // Create a copy of the list to avoid ConcurrentModificationException List<DiagnosticWrapper> diagnostics = new ArrayList<>(texts); this.diags = diagnostics; for (DiagnosticWrapper diagnostic : diagnostics) { if (diagnostic != null) { if (diagnostic.getKind() != null) { mEditor.setText(diagnostic.getKind().name()); combinedText.append(diagnostic.getKind().name()).append(": "); addDiagnosticSpan(combinedText, diagnostic); combinedText.append(' '); } if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { actionFab.setVisibility(View.VISIBLE); actionFab.setImageResource(R.drawable.ic_error); combinedText.append(diagnostic.getMessage(Locale.getDefault())); } else { String msg = diagnostic.getMessage(Locale.getDefault()); if (msg.contains("Generated APK has been saved")) { actionFab.setVisibility(View.VISIBLE); actionFab.setImageResource(R.drawable.apk_install); } else { actionFab.setVisibility(View.GONE); } combinedText.append(msg); } if (diagnostic.getSource() != null) { combinedText.append(' '); } combinedText.append("\n"); } } } mEditor.setText(combinedText); }, 100); } } @Override public void onProjectOpen(Project project) {} @ColorInt private int getColor(Diagnostic.Kind kind) { switch (kind) { case ERROR: return 0xffcf6679; case MANDATORY_WARNING: case WARNING: return Color.YELLOW; case NOTE: return Color.CYAN; default: return 0xffFFFFFF; } } private void addDiagnosticSpan(SpannableStringBuilder sb, DiagnosticWrapper diagnostic) { if (diagnostic.getSource() == null || !diagnostic.getSource().exists()) { return; } if (diagnostic.getOnClickListener() != null) { ClickableSpan span = new ClickableSpan() { @Override public void onClick(@NonNull View widget) { diagnostic.getOnClickListener().onClick(widget); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(getColor(diagnostic.getKind())); // set color ds.setUnderlineText(false); // underline the link text } }; sb.append("[" + diagnostic.getExtra() + "]", span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return; } ClickableSpan span = new ClickableSpan() { @Override public void onClick(@NonNull View view) { if (mListener != null) { mListener.onClick(diagnostic); } } }; String label = diagnostic.getSource().getName(); label = label + ":" + diagnostic.getLineNumber(); sb.append("[" + label + "]", span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } public interface OnDiagnosticClickListener { void onClick(DiagnosticWrapper diagnostic); } public void setOnDiagnosticClickListener(OnDiagnosticClickListener listener) { mListener = listener; } class ErrorItem { private String message; private String path; private DiagnosticWrapper diagnostic; public ErrorItem(String message, String path, DiagnosticWrapper diagnostic) { this.message = message; this.path = path; this.diagnostic = diagnostic; } public ErrorItem(String message, File path, DiagnosticWrapper diagnostic) { this.message = message; this.path = path.getAbsolutePath(); this.diagnostic = diagnostic; } public String getMessage() { return message; } private DiagnosticWrapper getDiagnosticWrapper() { return diagnostic; } public String getPath() { return path; } public File getFile() { return new File(path); } } }
16,629
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LogAdapter.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/editor/log/adapter/LogAdapter.java
package com.tyron.code.ui.editor.log.adapter; import android.graphics.Color; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.core.content.res.ResourcesCompat; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.RecyclerView; import com.tyron.builder.model.DiagnosticWrapper; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.tools.Diagnostic; import org.codeassist.unofficial.R; public class LogAdapter extends RecyclerView.Adapter<LogAdapter.ViewHolder> { public interface OnClickListener { void onClick(DiagnosticWrapper diagnostic); } private final List<DiagnosticWrapper> mData = new ArrayList<>(); private OnClickListener mListener; public LogAdapter() {} public void setListener(OnClickListener listener) { mListener = listener; } public void submitList(List<DiagnosticWrapper> newData) { DiffUtil.DiffResult result = DiffUtil.calculateDiff( new DiffUtil.Callback() { @Override public int getOldListSize() { return mData.size(); } @Override public int getNewListSize() { return newData.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return mData.get(oldItemPosition).equals(newData.get(newItemPosition)); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return mData.get(oldItemPosition).equals(newData.get(newItemPosition)); } }); mData.clear(); mData.addAll(newData); try { result.dispatchUpdatesTo(this); } catch (IndexOutOfBoundsException e) { notifyDataSetChanged(); } } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { FrameLayout layout = new FrameLayout(parent.getContext()); layout.setLayoutParams( new RecyclerView.LayoutParams( RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); return new ViewHolder(layout); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.bind(mData.get(position)); } @Override public int getItemCount() { return mData.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public TextView textView; public ViewHolder(FrameLayout layout) { super(layout); textView = new TextView(layout.getContext()); textView.setTextSize(12); textView.setTypeface( ResourcesCompat.getFont(layout.getContext(), R.font.jetbrains_mono_regular)); textView.setMovementMethod(LinkMovementMethod.getInstance()); layout.addView(textView); } public void bind(DiagnosticWrapper diagnostic) { SpannableStringBuilder builder = new SpannableStringBuilder(); if (diagnostic.getKind() != null) { builder.append( diagnostic.getKind().name() + ": ", new ForegroundColorSpan(getColor(diagnostic.getKind())), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { builder.append( diagnostic.getMessage(Locale.getDefault()), new ForegroundColorSpan(getColor(diagnostic.getKind())), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { builder.append(diagnostic.getMessage(Locale.getDefault())); } if (diagnostic.getSource() != null) { builder.append(' '); addClickableFile(builder, diagnostic); } textView.setText(builder); } } @ColorInt private int getColor(Diagnostic.Kind kind) { switch (kind) { case ERROR: return 0xffcf6679; case MANDATORY_WARNING: case WARNING: return Color.YELLOW; case NOTE: return Color.CYAN; default: return 0xffFFFFFF; } } private void addClickableFile(SpannableStringBuilder sb, final DiagnosticWrapper diagnostic) { if (diagnostic.getSource() == null || !diagnostic.getSource().exists()) { return; } if (diagnostic.getOnClickListener() != null) { ClickableSpan span = new ClickableSpan() { @Override public void onClick(@NonNull View widget) { diagnostic.getOnClickListener().onClick(widget); } }; sb.append("[" + diagnostic.getExtra() + "]", span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return; } ClickableSpan span = new ClickableSpan() { @Override public void onClick(@NonNull View view) { if (mListener != null) { mListener.onClick(diagnostic); } } }; String label = diagnostic.getSource().getName(); label = label + ":" + diagnostic.getLineNumber(); sb.append("[" + label + "]", span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } }
5,484
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileViewModel.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/FileViewModel.java
package com.tyron.code.ui.file; import android.os.Environment; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.tyron.code.ui.file.tree.TreeUtil; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.completion.progress.ProgressManager; import com.tyron.ui.treeview.TreeNode; import java.io.File; public class FileViewModel extends ViewModel { private MutableLiveData<File> mRoot = new MutableLiveData<>(Environment.getExternalStorageDirectory()); private MutableLiveData<TreeNode<TreeFile>> mNode = new MutableLiveData<>(); public LiveData<TreeNode<TreeFile>> getNodes() { return mNode; } public LiveData<File> getRootFile() { return mRoot; } public void setRootFile(File root) { mRoot.setValue(root); refreshNode(root); } public void setRootNode(TreeNode<TreeFile> rootNode) { mNode.setValue(rootNode); } public void refreshNode(File root) { ProgressManager.getInstance() .runNonCancelableAsync( () -> { TreeNode<TreeFile> node = TreeNode.root(TreeUtil.getNodes(root)); mNode.postValue(node); }); } }
1,217
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileManagerAdapter.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/FileManagerAdapter.java
package com.tyron.code.ui.file; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.codeassist.unofficial.R; public class FileManagerAdapter extends RecyclerView.Adapter<FileManagerAdapter.ViewHolder> { private static final int TYPE_NORMAL = 0; private static final int TYPE_BACK = 1; public interface OnItemClickListener { void onItemClick(File file, int position); } private OnItemClickListener mListener; private final List<File> mFiles = new ArrayList<>(); public void setOnItemClickListener(OnItemClickListener listener) { mListener = listener; } public void submitFile(File file) { mFiles.clear(); File[] files = file.listFiles(); if (files != null) { mFiles.addAll(List.of(files)); } Collections.sort( mFiles, (p1, p2) -> { if (p1.isFile() && p2.isFile()) { return p1.getName().compareTo(p2.getName()); } if (p1.isFile() && p2.isDirectory()) { return -1; } if (p1.isDirectory() && p2.isDirectory()) { return p1.getName().compareTo(p2.getName()); } return 0; }); notifyDataSetChanged(); } @NonNull @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int p2) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.file_manager_item, parent, false); final ViewHolder holder = new ViewHolder(view); if (mListener != null) { view.setOnClickListener( v -> { int position = holder.getBindingAdapterPosition(); if (position != RecyclerView.NO_POSITION) { File selected = null; if (position != 0) { selected = mFiles.get(position - 1); } mListener.onItemClick(selected, position); } }); } return holder; } @Override public void onBindViewHolder(ViewHolder holder, int p2) { int type = holder.getItemViewType(); if (type == TYPE_BACK) { holder.bindBack(); } else { holder.bind(mFiles.get(p2 - 1)); } } @Override public int getItemCount() { return mFiles.size() + 1; } @Override public int getItemViewType(int position) { if (position == 0) { return TYPE_BACK; } return TYPE_NORMAL; } public static class ViewHolder extends RecyclerView.ViewHolder { public ImageView icon; public TextView name; public ViewHolder(View view) { super(view); icon = view.findViewById(R.id.icon); name = view.findViewById(R.id.name); } public void bind(File file) { name.setText(file.getName()); if (file.isDirectory()) { icon.setImageResource(R.drawable.round_folder_24); } else if (file.isFile()) { icon.setImageResource(R.drawable.round_insert_drive_file_24); } } public void bindBack() { name.setText("..."); icon.setImageResource(R.drawable.round_arrow_upward_24); } } }
3,341
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
RegexReason.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/RegexReason.java
package com.tyron.code.ui.file; import android.os.Parcel; import android.os.Parcelable; import com.tyron.code.ui.file.dialog.CreateClassDialogFragment; /** * Class that holds a Regex String and a reason if the regex doesn't match. * * <p>This is used by {@link CreateClassDialogFragment} to check if the class name is a valid class * name, certain providers may have different name requirements such as an xml file, in android xml * files can only have lowercase letters and an underscore. */ public class RegexReason implements Parcelable { private String regexString; private String reason; public RegexReason(String regexString, String reason) { this.regexString = regexString; this.reason = reason; } public String getRegexString() { return regexString; } public String getReason() { return reason; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.regexString); dest.writeString(this.reason); } public void readFromParcel(Parcel source) { this.regexString = source.readString(); this.reason = source.readString(); } protected RegexReason(Parcel in) { this.regexString = in.readString(); this.reason = in.readString(); } public static final Parcelable.Creator<RegexReason> CREATOR = new Parcelable.Creator<RegexReason>() { @Override public RegexReason createFromParcel(Parcel source) { return new RegexReason(source); } @Override public RegexReason[] newArray(int size) { return new RegexReason[size]; } }; }
1,684
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CommonFileKeys.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/CommonFileKeys.java
package com.tyron.code.ui.file; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import org.jetbrains.kotlin.com.intellij.openapi.util.Key; public class CommonFileKeys { public static final Key<TreeNode<TreeFile>> TREE_NODE = Key.create("treeFile"); }
298
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FilePickerDialogFixed.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/FilePickerDialogFixed.java
package com.tyron.code.ui.file; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.TextView; import com.github.angads25.filepicker.controller.adapters.FileListAdapter; import com.github.angads25.filepicker.model.DialogProperties; import com.github.angads25.filepicker.model.MarkedItemList; import com.github.angads25.filepicker.view.FilePickerDialog; import java.lang.reflect.Field; public class FilePickerDialogFixed extends FilePickerDialog { public FilePickerDialogFixed(Context context) { super(context); } public FilePickerDialogFixed(Context context, DialogProperties properties) { super(context, properties); } public FilePickerDialogFixed(Context context, DialogProperties properties, int themeResId) { super(context, properties, themeResId); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onStart() { super.onStart(); Button cancel = findViewById(com.github.angads25.filepicker.R.id.cancel); Button select = findViewById(com.github.angads25.filepicker.R.id.select); String positiveButtonNameStr = getContext().getString(com.github.angads25.filepicker.R.string.choose_button_label); cancel.setTextColor(Color.WHITE); select.setTextColor(Color.WHITE); try { Field mAdapterField = FilePickerDialog.class.getDeclaredField("mFileListAdapter"); mAdapterField.setAccessible(true); FileListAdapter adapter = (FileListAdapter) mAdapterField.get(this); assert adapter != null; adapter.setNotifyItemCheckedListener( () -> { int size = MarkedItemList.getFileCount(); if (size == 0) { select.setEnabled(false); select.setTextColor(Color.WHITE); select.setText(positiveButtonNameStr); } else { select.setEnabled(true); select.setText(positiveButtonNameStr + " (" + size + ") "); } adapter.notifyDataSetChanged(); }); } catch (NoSuchFieldException | IllegalAccessException e) { Log.w("WizardFragment", "Unable to get declared field", e); } } /** * Return the current path of the current directory * * @return the absolute path of the directory */ public String getCurrentPath() { TextView path = findViewById(com.github.angads25.filepicker.R.id.dir_path); return String.valueOf(path.getText()); } }
2,596
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeFileManagerFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/tree/TreeFileManagerFragment.java
package com.tyron.code.ui.file.tree; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.PopupMenu; import androidx.core.view.ViewCompat; import androidx.documentfile.provider.DocumentFile; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.preference.PreferenceManager; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.android.material.button.MaterialButton; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputLayout; import com.tyron.actions.ActionManager; import com.tyron.actions.ActionPlaces; import com.tyron.actions.CommonDataKeys; import com.tyron.actions.DataContext; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.JavaModule; import com.tyron.builder.project.api.Module; import com.tyron.code.ApplicationLoader; import com.tyron.code.event.EventManager; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.FileViewModel; import com.tyron.code.ui.file.event.RefreshRootEvent; import com.tyron.code.ui.file.tree.binder.TreeFileNodeViewBinder.TreeFileNodeListener; import com.tyron.code.ui.file.tree.binder.TreeFileNodeViewFactory; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.code.ui.main.MainViewModel; import com.tyron.code.ui.project.ProjectManager; import com.tyron.code.util.UiUtilsKt; import com.tyron.common.util.AndroidUtilities; import com.tyron.common.util.SingleTextWatcher; import com.tyron.completion.progress.ProgressManager; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.apache.commons.io.FileUtils; import org.codeassist.unofficial.R; public class TreeFileManagerFragment extends Fragment { /** * @deprecated Instantiate this fragment directly without arguments and use {@link FileViewModel} * to update the nodes */ @Deprecated public static TreeFileManagerFragment newInstance(File root) { TreeFileManagerFragment fragment = new TreeFileManagerFragment(); Bundle args = new Bundle(); args.putSerializable("rootFile", root); fragment.setArguments(args); return fragment; } private ActivityResultLauncher<Intent> documentPickerLauncher; private File rootDir; private File currentDir; private MainViewModel mMainViewModel; private FileViewModel mFileViewModel; private TreeView<TreeFile> treeView; public TreeFileManagerFragment() { super(R.layout.tree_file_manager_fragment); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mMainViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class); mFileViewModel = new ViewModelProvider(requireActivity()).get(FileViewModel.class); documentPickerLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK) { Intent data = result.getData(); if (data != null) { Uri uri = data.getData(); if (uri != null) { String name = Objects.requireNonNull(DocumentFile.fromSingleUri(requireContext(), uri)) .getName(); try { InputStream inputStream = requireContext().getContentResolver().openInputStream(uri); File outputFile = new File(currentDir, name); FileUtils.copyInputStreamToFile(inputStream, outputFile); } catch (IOException ex) { ProgressManager.getInstance() .runLater( () -> { if (isDetached() || getContext() == null) { return; } AndroidUtilities.showSimpleAlert( requireContext(), R.string.error, ex.getLocalizedMessage()); }); } TreeNode<TreeFile> node = TreeNode.root(TreeUtil.getNodes(rootDir)); ProgressManager.getInstance() .runLater( () -> { if (getActivity() == null) { return; } treeView.refreshTreeView(node); }); } } } }); } @SuppressLint("ClickableViewAccessibility") @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { ViewCompat.requestApplyInsets(view); UiUtilsKt.addSystemWindowInsetToPadding(view, false, true, false, true); SwipeRefreshLayout refreshLayout = view.findViewById(R.id.refreshLayout); refreshLayout.setOnRefreshListener( () -> partialRefresh( () -> { refreshLayout.setRefreshing(false); treeView.refreshTreeView(); })); treeView = new TreeView<>(requireContext(), TreeNode.root(Collections.emptyList())); MaterialButton addLibrary = view.findViewById(R.id.addNewLibrary); MaterialButton projectInfo = view.findViewById(R.id.projectProperties); addLibrary.setOnClickListener( v -> { showNewLibrary(); }); projectInfo.setOnClickListener( v -> { showProjectInfo(); }); HorizontalScrollView horizontalScrollView = view.findViewById(R.id.horizontalScrollView); horizontalScrollView.addView( treeView.getView(), new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); treeView.getView().setNestedScrollingEnabled(false); EventManager eventManager = ApplicationLoader.getInstance().getEventManager(); eventManager.subscribeEvent( getViewLifecycleOwner(), RefreshRootEvent.class, (event, unsubscribe) -> { File refreshRoot = event.getRoot(); TreeNode<TreeFile> currentRoot = treeView.getRoot(); if (currentRoot != null && refreshRoot.equals(currentRoot.getValue().getFile())) { partialRefresh(() -> treeView.refreshTreeView()); } else { ProgressManager.getInstance() .runNonCancelableAsync( () -> { TreeNode<TreeFile> node = TreeNode.root(TreeUtil.getNodes(refreshRoot)); ProgressManager.getInstance() .runLater( () -> { if (getActivity() == null) { return; } treeView.refreshTreeView(node); }); }); } }); treeView.setAdapter( new TreeFileNodeViewFactory( new TreeFileNodeListener() { @Override public void onNodeToggled(TreeNode<TreeFile> treeNode, boolean expanded) { if (treeNode.isLeaf()) { if (treeNode.getValue().getFile().isFile()) { FileEditorManagerImpl.getInstance() .openFile(requireContext(), treeNode.getValue().getFile(), true); } } } @Override public boolean onNodeLongClicked( View view, TreeNode<TreeFile> treeNode, boolean expanded) { PopupMenu popupMenu = new PopupMenu(requireContext(), view); addMenus(popupMenu, treeNode); // Get the background drawable and set its shape try { Field popupField = PopupMenu.class.getDeclaredField("mPopup"); popupField.setAccessible(true); Object menuPopupHelper = popupField.get(popupMenu); Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); setForceIcons.invoke(menuPopupHelper, true); PopupWindow popupWindow = (PopupWindow) menuPopupHelper .getClass() .getDeclaredField("mPopup") .get(menuPopupHelper); popupWindow.setBackgroundDrawable( getResources().getDrawable(R.drawable.rounded_popup_menu_background, null)); } catch (Exception e) { e.printStackTrace(); } popupMenu.show(); return true; } })); mFileViewModel .getNodes() .observe( getViewLifecycleOwner(), node -> { treeView.refreshTreeView(node); }); } private void showNewLibrary() { // Inflate the view LayoutInflater inflater = LayoutInflater.from(requireContext()); View layout = inflater.inflate(R.layout.add_new_library_dialog, null); ProjectManager manager = ProjectManager.getInstance(); Project project = manager.getCurrentProject(); Module module = project.getMainModule(); JavaModule javaModule = (JavaModule) module; AlertDialog dialog = new MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.new_library) .setPositiveButton(R.string.create, null) .setNegativeButton(android.R.string.cancel, null) .setView(layout) .create(); dialog.setOnShowListener( d -> { final TextInputLayout nameLayout = layout.findViewById(R.id.name); final TextInputLayout packageNameLayout = layout.findViewById(R.id.packageName); final EditText nameEditText = nameLayout.getEditText(); final EditText packageNameEditText = packageNameLayout.getEditText(); final Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE); button.setEnabled(false); SingleTextWatcher textWatcher = new SingleTextWatcher() { @Override public void afterTextChanged(Editable editable) { String name = nameEditText.getText().toString(); String packageName = packageNameEditText.getText().toString(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(packageName)) { button.setEnabled(false); } else if (packageName.endsWith(".") || packageName.contains(" ")) { button.setEnabled(false); } else { boolean isLibraryExists = false; List<String> implementationProjects = javaModule.getAllProjects(); for (String implementationProject : implementationProjects) { if (implementationProject.contains(name)) { isLibraryExists = true; break; } } if (isLibraryExists) { nameLayout.setError("Library with this name already exists."); button.setEnabled(false); } else { nameLayout.setError(null); button.setEnabled(true); } } } }; SingleTextWatcher textWatcher2 = new SingleTextWatcher() { @Override public void afterTextChanged(Editable editable) { String name = nameEditText.getText().toString(); String packageName = packageNameEditText.getText().toString(); String package_name = editable.toString(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(package_name) || packageName.endsWith(".") || package_name.contains(" ")) { button.setEnabled(false); } else { boolean isLibraryExists = false; List<String> implementationProjects = javaModule.getAllProjects(); for (String implementationProject : implementationProjects) { if (implementationProject.contains(name)) { isLibraryExists = true; break; } } if (isLibraryExists) { nameLayout.setError("Library with this name already exists."); button.setEnabled(false); } else { nameLayout.setError(null); button.setEnabled(true); } } } }; nameEditText.addTextChangedListener(textWatcher); packageNameEditText.addTextChangedListener(textWatcher2); button.setOnClickListener( v -> { String name = nameEditText.getText().toString(); String packageName = packageNameEditText.getText().toString(); addLibrary(javaModule.getGradleFile(), name); File root = new File(module.getProjectDir(), "settings.gradle"); addToInclude(root, name); createAndroidLibrary(module.getProjectDir(), packageName, name); dialog.dismiss(); }); }); dialog.show(); } private void createAndroidLibrary(File root, String packageName, String name) { // Create the library directory structure File libraryDir = new File(root, name); File srcDir = new File(libraryDir, "src/main/java/" + packageName.replace(".", "/")); File resDir = new File(libraryDir, "src/main/res"); File manifestFile = new File(libraryDir, "src/main/AndroidManifest.xml"); if (!libraryDir.exists()) { libraryDir.mkdirs(); } if (!srcDir.exists()) { srcDir.mkdirs(); } if (!resDir.exists()) { resDir.mkdirs(); } // Create the build.gradle file String gradleCode = "plugins {\n" + " id 'com.android.library'\n" + "}\n" + "\n" + "android {\n" + " compileSdkVersion 34\n" + " namespace " + "\"" + packageName + "\"\n" + "\n" + " defaultConfig {\n" + " minSdkVersion 21\n" + " targetSdkVersion 34\n" + " versionCode 1\n" + " versionName \"1.0\"\n" + " }\n" + "\n" + " buildTypes {\n" + " release {\n" + " minifyEnabled false\n" + " proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n" + " }\n" + " }\n" + "\n" + " compileOptions {\n" + " sourceCompatibility JavaVersion.VERSION_1_8\n" + " targetCompatibility JavaVersion.VERSION_1_8\n" + " }\n" + "}\n" + "\n" + "dependencies {\n" + " implementation fileTree(dir: 'libs', include: ['*.jar'])\n" + "}"; File gradleFile = new File(libraryDir, "build.gradle"); try { gradleFile.createNewFile(); FileWriter gradleWriter = new FileWriter(gradleFile); gradleWriter.write(gradleCode); gradleWriter.close(); } catch (IOException e) { e.printStackTrace(); } // Create the Android Manifest file String manifestCode = "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" + " package=\"" + packageName + "\"\n" + " android:versionCode=\"1\"\n" + " android:versionName=\"1.0\">\n" + "\n" + "</manifest>"; try { manifestFile.createNewFile(); FileWriter manifestWriter = new FileWriter(manifestFile); manifestWriter.write(manifestCode); manifestWriter.close(); } catch (IOException e) { e.printStackTrace(); } // Create the strings.xml file File resFile = new File(resDir, "values/strings.xml"); try { resFile.getParentFile().mkdirs(); resFile.createNewFile(); FileWriter resWriter = new FileWriter(resFile); resWriter.write( "<resources>\n" + " <string name=\"library_name\">" + name + "</string>\n" + "</resources>"); resWriter.close(); } catch (IOException e) { e.printStackTrace(); } // Create a sample Java file File javaFile = new File(srcDir, "Library.java"); String javaCode = "package " + packageName + ";\n\n" + "public class Library {\n\n" + " public static String getMessage() {\n" + " return \"Hello from the library!\";\n" + " }\n\n" + "}\n"; try { FileWriter writer = new FileWriter(javaFile); writer.write(javaCode); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private void showProjectInfo() { ProjectManager manager = ProjectManager.getInstance(); Project project = manager.getCurrentProject(); Module module = project.getMainModule(); JavaModule javaModule = (JavaModule) module; String root = javaModule.getRootFile().getName(); LayoutInflater inflater = (LayoutInflater) requireContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.dialog_project_information, null); TextView projectPath = v.findViewById(R.id.projectPath); TextView libraryProjects = v.findViewById(R.id.libraryProjects); TextView includedProjects = v.findViewById(R.id.includedProjects); TextView projectLibraries = v.findViewById(R.id.projectLibraries); File prPath = javaModule.getRootFile(); String pr = root.substring(0, 1).toUpperCase() + root.substring(1) + " " + prPath.getAbsolutePath(); projectPath.setText(pr); List<String> implementationProjects = javaModule.getAllProjects(); List<String> included = javaModule.getIncludedProjects(); String implementationText = implementationProjects.isEmpty() ? "sub projects: <none>" : "sub projects:\n" + String.join("\n", implementationProjects); libraryProjects.setText(implementationText); String includedText = included.isEmpty() ? "included projects: <none>" : "included projects:\n" + String.join("\n", included); includedProjects.setText(includedText); File[] fileLibraries = getProjectLibraries(javaModule.getLibraryDirectory()); if (fileLibraries != null && fileLibraries.length > 0) { StringBuilder libraryTextBuilder = new StringBuilder(prPath.getName() + " libraries:\n"); for (File fileLibrary : fileLibraries) { libraryTextBuilder.append(fileLibrary.getName()).append("\n"); } String libraryText = libraryTextBuilder.toString().trim(); projectLibraries.setText(libraryText); } else { projectLibraries.setText(prPath.getName() + " libraries: <none>"); } new MaterialAlertDialogBuilder(requireContext()) .setTitle("Project " + "'" + root + "'") .setView(v) .setPositiveButton(android.R.string.ok, null) .setNeutralButton( R.string.variants, (d, w) -> { showBuildVariants(); }) .show(); } private static final String LAST_SELECTED_INDEX_KEY = "last_selected_index"; private int lastSelectedIndex = 0; private void showBuildVariants() { List<String> variants = new ArrayList<>(); variants.add("Release"); variants.add("Debug"); final String[] options = variants.toArray(new String[0]); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(requireContext()); int defaultSelection = preferences.getInt(LAST_SELECTED_INDEX_KEY, 1); lastSelectedIndex = defaultSelection; new MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.build_variants) .setSingleChoiceItems( options, defaultSelection, (dialog, which) -> { lastSelectedIndex = which; preferences.edit().putInt(LAST_SELECTED_INDEX_KEY, which).apply(); }) .setPositiveButton( android.R.string.ok, (dialog, which) -> { String selectedVariant = options[lastSelectedIndex]; if (defaultSelection != lastSelectedIndex) { String message = getString(R.string.switched_to_variant) + " " + selectedVariant; Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show(); } }) .show(); } private File[] getProjectLibraries(File dir) { File[] fileLibraries = dir.listFiles(c -> c.getName().endsWith(".aar") || c.getName().endsWith(".jar")); return fileLibraries; } private void partialRefresh(Runnable callback) { ProgressManager.getInstance() .runNonCancelableAsync( () -> { if (!treeView.getAllNodes().isEmpty()) { TreeNode<TreeFile> node = treeView.getAllNodes().get(0); TreeUtil.updateNode(node); ProgressManager.getInstance() .runLater( () -> { if (getActivity() == null) { return; } callback.run(); }); } }); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); } /** * Add menus to the current PopupMenu based on the current {@link TreeNode} * * @param popupMenu The PopupMenu to add to * @param node The current TreeNode in the file tree */ private void addMenus(PopupMenu popupMenu, TreeNode<TreeFile> node) { DataContext dataContext = DataContext.wrap(requireContext()); dataContext.putData(CommonDataKeys.FILE, node.getContent().getFile()); dataContext.putData(CommonDataKeys.PROJECT, ProjectManager.getInstance().getCurrentProject()); dataContext.putData(CommonDataKeys.FRAGMENT, TreeFileManagerFragment.this); dataContext.putData(CommonDataKeys.ACTIVITY, requireActivity()); dataContext.putData(CommonFileKeys.TREE_NODE, node); ActionManager.getInstance() .fillMenu(dataContext, popupMenu.getMenu(), ActionPlaces.FILE_MANAGER, true, false); } public TreeView<TreeFile> getTreeView() { return treeView; } public MainViewModel getMainViewModel() { return mMainViewModel; } public FileViewModel getFileViewModel() { return mFileViewModel; } private void addLibrary(File gradleFile, String name) { String dependencyLine = "\timplementation project(':" + name + "')\n"; try { // Read the contents of the build.gradle file FileInputStream inputStream = new FileInputStream(gradleFile); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { // Add the dependency line after the last line that starts with "dependencies {" if (line.trim().startsWith("dependencies {")) { stringBuilder.append(line).append("\n"); while ((line = reader.readLine()) != null) { stringBuilder.append(line).append("\n"); } stringBuilder.insert(stringBuilder.lastIndexOf("}"), dependencyLine); break; } else { stringBuilder.append(line).append("\n"); } } inputStream.close(); // Write the modified contents back to the build.gradle file FileOutputStream outputStream = new FileOutputStream(gradleFile); outputStream.write(stringBuilder.toString().getBytes()); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } private void addToInclude(File gradleSettingsFile, String name) { String includeLine = "include ':" + name + "'\n"; try { // Read the contents of the settings.gradle file FileInputStream inputStream = new FileInputStream(gradleSettingsFile); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; boolean includeExists = false; while ((line = reader.readLine()) != null) { // Check if the include line already exists if (line.trim().equals(includeLine.trim())) { includeExists = true; } stringBuilder.append(line).append("\n"); } inputStream.close(); // Add the include line if it does not already exist if (!includeExists) { stringBuilder.append(includeLine); } // Write the modified contents back to the settings.gradle file FileOutputStream outputStream = new FileOutputStream(gradleSettingsFile); outputStream.write(stringBuilder.toString().getBytes()); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public void importFile(File rootDir, File currentDir) { this.rootDir = rootDir; this.currentDir = currentDir; Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("*/*"); documentPickerLauncher.launch(intent); } }
27,876
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeUtil.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/tree/TreeUtil.java
package com.tyron.code.ui.file.tree; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; public class TreeUtil { public static final Comparator<File> FILE_FIRST_ORDER = (file1, file2) -> { if (file1.isFile() && file2.isDirectory()) { return 1; } else if (file2.isFile() && file1.isDirectory()) { return -1; } else { return String.CASE_INSENSITIVE_ORDER.compare(file1.getName(), file2.getName()); } }; public static TreeNode<TreeFile> getRootNode(TreeNode<TreeFile> node) { TreeNode<TreeFile> parent = node.getParent(); TreeNode<TreeFile> root = node; while (parent != null) { root = parent; parent = parent.getParent(); } return root; } public static void updateNode(TreeNode<TreeFile> node) { Set<File> expandedNodes = TreeUtil.getExpandedNodes(node); List<TreeNode<TreeFile>> newChildren = getNodes(node.getValue().getFile(), node.getLevel()).get(0).getChildren(); setExpandedNodes(newChildren, expandedNodes); node.setChildren(newChildren); } private static void setExpandedNodes(List<TreeNode<TreeFile>> nodeList, Set<File> expandedNodes) { for (TreeNode<TreeFile> treeFileTreeNode : nodeList) { if (expandedNodes.contains(treeFileTreeNode.getValue().getFile())) { treeFileTreeNode.setExpanded(true); } setExpandedNodes(treeFileTreeNode.getChildren(), expandedNodes); } } private static Set<File> getExpandedNodes(TreeNode<TreeFile> node) { Set<File> expandedNodes = new HashSet<>(); if (node.isExpanded()) { expandedNodes.add(node.getValue().getFile()); } for (TreeNode<TreeFile> child : node.getChildren()) { if (child.getValue().getFile().isDirectory()) { expandedNodes.addAll(getExpandedNodes(child)); } } return expandedNodes; } public static List<TreeNode<TreeFile>> getNodes(File rootFile) { return getNodes(rootFile, 0); } /** Get all the tree note at the given root */ public static List<TreeNode<TreeFile>> getNodes(File rootFile, int initialLevel) { List<TreeNode<TreeFile>> nodes = new ArrayList<>(); if (rootFile == null) { return nodes; } TreeNode<TreeFile> root = new TreeNode<>(TreeFile.fromFile(rootFile), initialLevel); root.setExpanded(true); File[] children = rootFile.listFiles(); if (children != null) { Arrays.sort(children, FILE_FIRST_ORDER); for (File file : children) { addNode(root, file, initialLevel + 1); } } nodes.add(root); return nodes; } private static void addNode(TreeNode<TreeFile> node, File file, int level) { TreeNode<TreeFile> childNode = new TreeNode<>(TreeFile.fromFile(file), level); if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { Arrays.sort(children, FILE_FIRST_ORDER); for (File child : children) { addNode(childNode, child, level + 1); } } } node.addChild(childNode); } }
3,280
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeFile.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/tree/model/TreeFile.java
package com.tyron.code.ui.file.tree.model; import android.content.Context; import android.graphics.drawable.Drawable; import androidx.annotation.Nullable; import androidx.appcompat.content.res.AppCompatResources; import java.io.File; import java.util.Objects; import org.codeassist.unofficial.R; public class TreeFile { @Nullable public static TreeFile fromFile(File file) { if (file == null) { return null; } if (file.isDirectory()) { return new TreeFolder(file); } if (file.getName().endsWith(".java")) { return new TreeJavaFile(file); } return new TreeFile(file); } private final File mFile; public TreeFile(File file) { mFile = file; } public File getFile() { return mFile; } public Drawable getIcon(Context context) { return AppCompatResources.getDrawable(context, R.drawable.round_insert_drive_file_24); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TreeFile treeFile = (TreeFile) o; return Objects.equals(mFile, treeFile.mFile); } @Override public int hashCode() { return Objects.hash(mFile); } }
1,238
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeFolder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/tree/model/TreeFolder.java
package com.tyron.code.ui.file.tree.model; import android.content.Context; import android.graphics.drawable.Drawable; import androidx.appcompat.content.res.AppCompatResources; import java.io.File; import org.codeassist.unofficial.R; public class TreeFolder extends TreeFile { public TreeFolder(File file) { super(file); } @Override public Drawable getIcon(Context context) { return AppCompatResources.getDrawable(context, R.drawable.round_folder_20); } }
477
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeJavaFile.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/tree/model/TreeJavaFile.java
package com.tyron.code.ui.file.tree.model; import android.content.Context; import android.graphics.drawable.Drawable; import java.io.File; public class TreeJavaFile extends TreeFile { public TreeJavaFile(File file) { super(file); } @Override public Drawable getIcon(Context context) { return super.getIcon(context); } }
342
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GitActionGroup.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/GitActionGroup.java
package com.tyron.code.ui.file.action; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tyron.actions.ActionGroup; import com.tyron.actions.AnAction; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.actions.Presentation; import com.tyron.builder.project.Project; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.git.GitAddToStageAction; import com.tyron.code.ui.file.action.git.GitCommitAction; import com.tyron.code.ui.file.action.git.GitRemoveFromIndexAction; import com.tyron.code.ui.file.action.git.GitRemoveFromIndexForceAction; import com.tyron.code.ui.file.action.git.GitResetChangesAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class GitActionGroup extends ActionGroup { public static final String ID = "fileManagerGitGroup"; private Project project; @Override public void update(@NonNull AnActionEvent event) { Presentation presentation = event.getPresentation(); presentation.setVisible(false); TreeNode<TreeFile> data = event.getData(CommonFileKeys.TREE_NODE); if (data == null) { return; } project = event.getData(CommonDataKeys.PROJECT); if (project == null) { return; } TreeFileManagerFragment fragment = (TreeFileManagerFragment) event.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = event.getRequiredData(CommonFileKeys.TREE_NODE); String path; File rootProject = project.getRootFile(); File gitConfig = new File(rootProject + "/.git/config"); File currentFile = currentNode.getValue().getFile(); if (currentFile.isDirectory()) { path = currentFile .getAbsolutePath() .substring((rootProject.getAbsolutePath() + "/app").lastIndexOf("/")); if (path.startsWith(".git")) { presentation.setVisible(false); } else if (path.isEmpty()) { presentation.setVisible(false); } } else if (gitConfig.exists()) { presentation.setVisible(true); } presentation.setText(event.getDataContext().getString(R.string.menu_git)); } @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { return new AnAction[] { new GitAddToStageAction(), new GitCommitAction(), new GitRemoveFromIndexAction(), new GitRemoveFromIndexForceAction(), new GitResetChangesAction() }; } }
2,728
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/FileAction.java
package com.tyron.code.ui.file.action; import android.content.Context; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.tyron.actions.ActionPlaces; import com.tyron.actions.AnAction; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.actions.Presentation; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import java.io.File; public abstract class FileAction extends AnAction { @Override public void update(@NonNull AnActionEvent event) { Presentation presentation = event.getPresentation(); presentation.setVisible(false); if (!ActionPlaces.FILE_MANAGER.equals(event.getPlace())) { return; } File file = event.getData(CommonDataKeys.FILE); if (file == null) { return; } if (!isApplicable(file)) { return; } Fragment fragment = event.getData(CommonDataKeys.FRAGMENT); if (!(fragment instanceof TreeFileManagerFragment)) { return; } presentation.setVisible(true); presentation.setText(getTitle(event.getDataContext())); } public abstract String getTitle(Context context); public abstract boolean isApplicable(File file); }
1,217
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
NewFileActionGroup.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/NewFileActionGroup.java
package com.tyron.code.ui.file.action; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tyron.actions.ActionGroup; import com.tyron.actions.AnAction; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.actions.Presentation; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.file.CreateDirectoryAction; import com.tyron.code.ui.file.action.file.CreateFileAction; import com.tyron.code.ui.file.action.java.CreateClassAction; import com.tyron.code.ui.file.action.kotlin.CreateKotlinClassAction; import com.tyron.code.ui.file.action.xml.CreateLayoutAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class NewFileActionGroup extends ActionGroup { public static final String ID = "fileManagerNewGroup"; @Override public void update(@NonNull AnActionEvent event) { Presentation presentation = event.getPresentation(); presentation.setVisible(false); TreeNode<TreeFile> data = event.getData(CommonFileKeys.TREE_NODE); if (data == null) { return; } TreeFileManagerFragment fragment = (TreeFileManagerFragment) event.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = event.getRequiredData(CommonFileKeys.TREE_NODE); File currentFile = currentNode.getValue().getFile(); if (currentFile.isDirectory()) { presentation.setVisible(true); } presentation.setText(event.getDataContext().getString(R.string.menu_new)); } @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { return new AnAction[] { new CreateFileAction(), new CreateClassAction(), new CreateKotlinClassAction(), new CreateLayoutAction(), new CreateDirectoryAction() }; } }
2,067
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ActionContext.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/ActionContext.java
package com.tyron.code.ui.file.action; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; public class ActionContext { private final TreeFileManagerFragment mFragment; private final TreeView<TreeFile> mTreeView; private final TreeNode<TreeFile> mCurrentNode; public ActionContext( TreeFileManagerFragment mFragment, TreeView<TreeFile> mTreeView, TreeNode<TreeFile> mCurrentNode) { this.mFragment = mFragment; this.mTreeView = mTreeView; this.mCurrentNode = mCurrentNode; } public TreeFileManagerFragment getFragment() { return mFragment; } public TreeView<TreeFile> getTreeView() { return mTreeView; } public TreeNode<TreeFile> getCurrentNode() { return mCurrentNode; } }
883
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ImportFileActionGroup.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/ImportFileActionGroup.java
package com.tyron.code.ui.file.action; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tyron.actions.ActionGroup; import com.tyron.actions.AnAction; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.actions.Presentation; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.file.ImportDirectoryAction; import com.tyron.code.ui.file.action.file.ImportFileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class ImportFileActionGroup extends ActionGroup { public static final String ID = "fileManagerImportGroup"; @Override public void update(@NonNull AnActionEvent event) { Presentation presentation = event.getPresentation(); presentation.setVisible(false); TreeNode<TreeFile> data = event.getData(CommonFileKeys.TREE_NODE); if (data == null) { return; } TreeFileManagerFragment fragment = (TreeFileManagerFragment) event.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = event.getRequiredData(CommonFileKeys.TREE_NODE); File currentFile = currentNode.getValue().getFile(); if (currentFile.isDirectory()) { presentation.setVisible(true); } presentation.setText(event.getDataContext().getString(R.string.menu_import)); } @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { return new AnAction[] {new ImportFileAction(), new ImportDirectoryAction()}; } }
1,767
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CreateClassAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/java/CreateClassAction.java
package com.tyron.code.ui.file.action.java; import android.content.Context; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.api.JavaModule; import com.tyron.builder.project.api.Module; import com.tyron.code.template.CodeTemplate; import com.tyron.code.template.java.AbstractTemplate; import com.tyron.code.template.java.InterfaceTemplate; import com.tyron.code.template.java.JavaClassTemplate; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.dialog.CreateClassDialogFragment; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.code.ui.project.ProjectManager; import com.tyron.code.util.ProjectUtils; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.codeassist.unofficial.R; public class CreateClassAction extends FileAction { @Override public boolean isApplicable(File file) { if (file.isDirectory()) { return ProjectUtils.getPackageName(file) != null; } return false; } @Override public String getTitle(Context context) { return context.getString(R.string.menu_action_new_java_class); } private List<CodeTemplate> getTemplates() { return Arrays.asList(new JavaClassTemplate(), new AbstractTemplate(), new InterfaceTemplate()); } @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); File file = e.getData(CommonDataKeys.FILE); TreeNode<TreeFile> treeNode = e.getData(CommonFileKeys.TREE_NODE); CreateClassDialogFragment dialogFragment = CreateClassDialogFragment.newInstance(getTemplates(), Collections.emptyList()); dialogFragment.show(fragment.getChildFragmentManager(), null); dialogFragment.setOnClassCreatedListener( (className, template) -> { try { File createdFile = ProjectManager.createClass(file, className, template); TreeNode<TreeFile> newNode = new TreeNode<>(TreeFile.fromFile(createdFile), treeNode.getLevel() + 1); if (createdFile == null) { throw new IOException("Unable to create file"); } treeView.addNode(treeNode, newNode); treeView.refreshTreeView(); FileEditorManagerImpl.getInstance() .openFile( fragment.requireContext(), createdFile, fileEditor -> fragment.getMainViewModel().openFile(fileEditor)); Module currentModule = ProjectManager.getInstance() .getCurrentProject() .getModule(treeNode.getContent().getFile()); if (currentModule instanceof JavaModule) { ((JavaModule) currentModule).addJavaFile(createdFile); } } catch (IOException exception) { new MaterialAlertDialogBuilder(fragment.requireContext()) .setMessage(exception.getMessage()) .setPositiveButton(android.R.string.ok, null) .setTitle(R.string.error) .show(); } }); } }
3,692
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CreateKotlinClassAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/kotlin/CreateKotlinClassAction.java
package com.tyron.code.ui.file.action.kotlin; import android.content.Context; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.api.KotlinModule; import com.tyron.builder.project.api.Module; import com.tyron.code.template.CodeTemplate; import com.tyron.code.template.kotlin.KotlinAbstractClassTemplate; import com.tyron.code.template.kotlin.KotlinClassTemplate; import com.tyron.code.template.kotlin.KotlinInterfaceTemplate; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.dialog.CreateClassDialogFragment; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.code.ui.project.ProjectManager; import com.tyron.code.util.ProjectUtils; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.codeassist.unofficial.R; public class CreateKotlinClassAction extends FileAction { @Override public String getTitle(Context context) { return context.getString(R.string.menu_action_new_kotlin_class); } @Override public boolean isApplicable(File file) { if (file.isDirectory()) { return ProjectUtils.getPackageName(file) != null; } return false; } @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = e.getData(CommonFileKeys.TREE_NODE); CreateClassDialogFragment dialogFragment = CreateClassDialogFragment.newInstance(getTemplates(), Collections.emptyList()); dialogFragment.show(fragment.getChildFragmentManager(), null); dialogFragment.setOnClassCreatedListener( (className, template) -> { try { File createdFile = ProjectManager.createClass(currentNode.getContent().getFile(), className, template); TreeNode<TreeFile> newNode = new TreeNode<>(TreeFile.fromFile(createdFile), currentNode.getLevel() + 1); treeView.addNode(currentNode, newNode); treeView.refreshTreeView(); FileEditorManagerImpl.getInstance() .openFile( fragment.requireContext(), createdFile, fileEditor -> fragment.getMainViewModel().openFile(fileEditor)); Module currentModule = ProjectManager.getInstance() .getCurrentProject() .getModule(currentNode.getContent().getFile()); if (currentModule instanceof KotlinModule) { ((KotlinModule) currentModule).addKotlinFile(createdFile); } } catch (IOException exception) { new MaterialAlertDialogBuilder(fragment.requireContext()) .setMessage(exception.getMessage()) .setPositiveButton(android.R.string.ok, null) .setTitle(R.string.error) .show(); } }); } private List<CodeTemplate> getTemplates() { return Arrays.asList( new KotlinClassTemplate(), new KotlinInterfaceTemplate(), new KotlinAbstractClassTemplate()); } }
3,671
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CreateDirectoryAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/file/CreateDirectoryAction.java
package com.tyron.code.ui.file.action.file; import android.content.Context; import android.content.DialogInterface; import android.text.Editable; import android.view.View; import android.widget.Button; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputLayout; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.TreeUtil; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.common.util.SingleTextWatcher; import com.tyron.completion.progress.ProgressManager; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class CreateDirectoryAction extends FileAction { public static final String ID = "fileManagerCreateDirectoryAction"; @Override public String getTitle(Context context) { return context.getString(R.string.menu_action_new_directory); } @Override public boolean isApplicable(File file) { return file.isDirectory(); } private void refreshTreeView(TreeNode<TreeFile> currentNode, TreeView<?> treeView) { TreeUtil.updateNode(currentNode); treeView.refreshTreeView(); } @SuppressWarnings("ConstantConditions") @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getData(CommonDataKeys.FRAGMENT); File currentDir = e.getData(CommonDataKeys.FILE); TreeNode<TreeFile> currentNode = e.getData(CommonFileKeys.TREE_NODE); AlertDialog dialog = new MaterialAlertDialogBuilder(fragment.requireContext()) .setView(R.layout.create_class_dialog) .setTitle(R.string.menu_action_new_directory) .setPositiveButton(R.string.create_class_dialog_positive, null) .setNegativeButton(android.R.string.cancel, null) .create(); dialog.setOnShowListener( (d) -> { dialog.findViewById(R.id.til_class_type).setVisibility(View.GONE); TextInputLayout til = dialog.findViewById(R.id.til_class_name); EditText editText = dialog.findViewById(R.id.et_class_name); Button positive = dialog.getButton(DialogInterface.BUTTON_POSITIVE); til.setHint(R.string.directory_name); positive.setOnClickListener( v -> { ProgressManager progress = ProgressManager.getInstance(); progress.runNonCancelableAsync( () -> { File fileToCreate = new File(currentDir, editText.getText().toString()); if (!fileToCreate.mkdirs()) { progress.runLater( () -> { new MaterialAlertDialogBuilder(fragment.requireContext()) .setTitle(R.string.error) .setMessage(R.string.error_dir_access) .setPositiveButton(android.R.string.ok, null) .show(); }); } else { progress.runLater( () -> { if (fragment == null || fragment.isDetached()) { return; } refreshTreeView(currentNode, fragment.getTreeView()); dialog.dismiss(); }); } }); }); editText.addTextChangedListener( new SingleTextWatcher() { @Override public void afterTextChanged(Editable editable) { File file = new File(currentDir, editable.toString()); positive.setEnabled(!file.exists()); } }); }); dialog.show(); } }
4,303
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
InstallApkFileAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/file/InstallApkFileAction.java
package com.tyron.code.ui.file.action.file; import android.content.Context; import androidx.annotation.NonNull; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.code.util.ApkInstaller; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class InstallApkFileAction extends FileAction { public static final String ID = "fileManagerInstallApkFileAction"; @Override public String getTitle(Context context) { return context.getString(R.string.install); } @Override public boolean isApplicable(File file) { return file.getName().endsWith(".apk"); } @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = e.getRequiredData(CommonFileKeys.TREE_NODE); ApkInstaller.installApplication( fragment.requireContext(), currentNode.getValue().getFile().getAbsolutePath()); } }
1,375
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ImportDirectoryAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/file/ImportDirectoryAction.java
package com.tyron.code.ui.file.action.file; import android.content.Context; import android.os.Build; import android.os.Environment; import androidx.annotation.NonNull; import com.github.angads25.filepicker.model.DialogConfigs; import com.github.angads25.filepicker.model.DialogProperties; import com.github.angads25.filepicker.view.FilePickerDialog; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.actions.Presentation; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.TreeUtil; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.common.util.AndroidUtilities; import com.tyron.completion.progress.ProgressManager; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.codeassist.unofficial.R; public class ImportDirectoryAction extends FileAction { public static final String ID = "fileManagerImportDirectoryAction"; @Override public String getTitle(Context context) { return context.getString(R.string.menu_action_new_directory); } @Override public boolean isApplicable(File file) { return file.isDirectory(); } @Override public void update(@NonNull AnActionEvent event) { Presentation presentation = event.getPresentation(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { presentation.setVisible(true); } else { presentation.setVisible(false); } } private void refreshTreeView(TreeNode<TreeFile> currentNode, TreeView<?> treeView) { TreeUtil.updateNode(currentNode); treeView.refreshTreeView(); } @SuppressWarnings("ConstantConditions") @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getData(CommonDataKeys.FRAGMENT); File currentDir = e.getData(CommonDataKeys.FILE); TreeNode<TreeFile> currentNode = e.getData(CommonFileKeys.TREE_NODE); DialogProperties properties = new DialogProperties(); properties.selection_mode = DialogConfigs.SINGLE_MODE; properties.selection_type = DialogConfigs.DIR_SELECT; properties.root = Environment.getExternalStorageDirectory(); properties.error_dir = fragment.requireContext().getExternalFilesDir(null); FilePickerDialog dialog = new FilePickerDialog(fragment.requireContext(), properties); dialog.setDialogSelectionListener( files -> { ProgressManager.getInstance() .runNonCancelableAsync( () -> { String file = files[0]; try { FileUtils.copyDirectoryToDirectory(new File(file), currentDir); } catch (IOException ioException) { ProgressManager.getInstance() .runLater( () -> { if (fragment.isDetached() || fragment.getContext() == null) { return; } AndroidUtilities.showSimpleAlert( e.getDataContext(), R.string.error, ioException.getLocalizedMessage()); }); } ProgressManager.getInstance() .runLater( () -> { if (fragment.isDetached() || fragment.getContext() == null) { return; } refreshTreeView(currentNode, fragment.getTreeView()); }); }); }); dialog.show(); } }
4,001
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CreateFileAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/file/CreateFileAction.java
package com.tyron.code.ui.file.action.file; import android.content.Context; import android.content.DialogInterface; import android.text.Editable; import android.view.View; import android.widget.Button; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputLayout; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.ActionContext; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.TreeUtil; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.code.ui.project.ProjectManager; import com.tyron.common.util.SingleTextWatcher; import com.tyron.completion.xml.task.InjectResourcesTask; import com.tyron.ui.treeview.TreeNode; import java.io.File; import java.io.IOException; import org.codeassist.unofficial.R; public class CreateFileAction extends FileAction { @Override public String getTitle(Context context) { return context.getString(R.string.menu_action_new_file); } @Override public boolean isApplicable(File file) { return file.isDirectory(); } @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getRequiredData(CommonDataKeys.FRAGMENT); TreeNode<TreeFile> currentNode = e.getRequiredData(CommonFileKeys.TREE_NODE); ActionContext actionContext = new ActionContext(fragment, fragment.getTreeView(), currentNode); onMenuItemClick(actionContext); } @SuppressWarnings("ConstantConditions") private void onMenuItemClick(ActionContext context) { File currentDir = context.getCurrentNode().getValue().getFile(); AlertDialog dialog = new MaterialAlertDialogBuilder(context.getFragment().requireContext()) .setView(R.layout.create_class_dialog) .setTitle(R.string.menu_action_new_file) .setPositiveButton(R.string.create_class_dialog_positive, null) .setNegativeButton(android.R.string.cancel, null) .create(); dialog.setOnShowListener( (d) -> { dialog.findViewById(R.id.til_class_type).setVisibility(View.GONE); TextInputLayout til = dialog.findViewById(R.id.til_class_name); EditText editText = dialog.findViewById(R.id.et_class_name); Button positive = dialog.getButton(DialogInterface.BUTTON_POSITIVE); til.setHint(R.string.file_name); positive.setOnClickListener( v -> { File fileToCreate = new File(currentDir, editText.getText().toString()); if (!createFileSilently(fileToCreate)) { new AlertDialog.Builder(context.getFragment().requireContext()) .setTitle(R.string.error) .setMessage(R.string.error_dir_access) .setPositiveButton(android.R.string.ok, null) .show(); } else { refreshTreeView(context); dialog.dismiss(); try { InjectResourcesTask.inject(ProjectManager.getInstance().getCurrentProject()); } catch (IOException e) { // ignored } } }); editText.addTextChangedListener( new SingleTextWatcher() { @Override public void afterTextChanged(Editable editable) { File file = new File(currentDir, editable.toString()); positive.setEnabled(!file.exists()); } }); }); dialog.show(); } private boolean createFileSilently(File file) { try { return file.createNewFile(); } catch (IOException e) { return false; } } private void refreshTreeView(ActionContext context) { TreeNode<TreeFile> currentNode = context.getCurrentNode(); TreeUtil.updateNode(currentNode); context.getTreeView().refreshTreeView(); } }
4,307
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DeleteFileAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/file/DeleteFileAction.java
package com.tyron.code.ui.file.action.file; import android.content.Context; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.api.FileManager; import com.tyron.builder.project.api.JavaModule; import com.tyron.builder.project.api.Module; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.TreeUtil; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.code.ui.project.ProjectManager; import com.tyron.common.util.StringSearch; import com.tyron.completion.progress.ProgressManager; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import java.io.IOException; import kotlin.io.FileWalkDirection; import kotlin.io.FilesKt; import org.apache.commons.io.FileUtils; import org.codeassist.unofficial.R; public class DeleteFileAction extends FileAction { public static final String ID = "fileManagerDeleteFileAction"; @Override public String getTitle(Context context) { return context.getString(R.string.dialog_delete); } @Override public boolean isApplicable(File file) { return true; } @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = e.getRequiredData(CommonFileKeys.TREE_NODE); new MaterialAlertDialogBuilder(fragment.requireContext()) .setMessage( String.format( fragment.getString(R.string.dialog_confirm_delete), currentNode.getValue().getFile().getName())) .setNegativeButton(android.R.string.no, null) .setPositiveButton( fragment.getString(R.string.dialog_delete), (d, which) -> { ProgressManager progress = ProgressManager.getInstance(); progress.runNonCancelableAsync( () -> { boolean success = deleteFiles(currentNode, fragment); progress.runLater( () -> { if (fragment.isDetached()) { return; } if (success) { treeView.deleteNode(currentNode); TreeUtil.updateNode(currentNode.getParent()); treeView.refreshTreeView(); FileEditorManagerImpl.getInstance() .closeFile(currentNode.getValue().getFile()); } else { new MaterialAlertDialogBuilder(fragment.requireContext()) .setTitle(R.string.error) .setMessage("Failed to delete file.") .setPositiveButton(android.R.string.ok, null) .show(); } }); }); }) .show(); } private boolean deleteFiles(TreeNode<TreeFile> currentNode, TreeFileManagerFragment fragment) { File currentFile = currentNode.getContent().getFile(); FilesKt.walk(currentFile, FileWalkDirection.TOP_DOWN) .iterator() .forEachRemaining( file -> { Module module = ProjectManager.getInstance().getCurrentProject().getModule(file); if (file.getName().endsWith(".java")) { // todo: add .kt and .xml checks ProgressManager.getInstance() .runLater(() -> fragment.getMainViewModel().removeFile(file)); if (module instanceof JavaModule) { String packageName = StringSearch.packageName(file); if (packageName != null) { packageName += "." + file.getName().substring(0, file.getName().lastIndexOf(".")); } ((JavaModule) module).removeJavaFile(packageName); } } ProgressManager.getInstance() .runLater( () -> { FileManager fileManager = module.getFileManager(); if (fileManager.isOpened(file)) { fileManager.closeFileForSnapshot(file); } }); }); try { FileUtils.forceDelete(currentFile); } catch (IOException e) { return false; } return true; } }
4,975
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ImportFileAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/file/ImportFileAction.java
package com.tyron.code.ui.file.action.file; import android.content.Context; import android.os.Build; import android.os.Environment; import androidx.annotation.NonNull; import com.github.angads25.filepicker.model.DialogConfigs; import com.github.angads25.filepicker.model.DialogProperties; import com.github.angads25.filepicker.view.FilePickerDialog; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.Project; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.TreeUtil; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.common.util.AndroidUtilities; import com.tyron.completion.progress.ProgressManager; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.codeassist.unofficial.R; public class ImportFileAction extends FileAction { public static final String ID = "fileManagerImportFileAction"; @Override public String getTitle(Context context) { return context.getString(R.string.menu_action_new_file); } @Override public boolean isApplicable(File file) { return file.isDirectory(); } private void refreshTreeView(TreeNode<TreeFile> currentNode, TreeView<?> treeView) { TreeUtil.updateNode(currentNode); treeView.refreshTreeView(); } @SuppressWarnings("ConstantConditions") @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getData(CommonDataKeys.FRAGMENT); File currentDir = e.getData(CommonDataKeys.FILE); TreeNode<TreeFile> currentNode = e.getData(CommonFileKeys.TREE_NODE); DialogProperties properties = new DialogProperties(); properties.selection_mode = DialogConfigs.MULTI_MODE; properties.selection_type = DialogConfigs.FILE_SELECT; properties.root = Environment.getExternalStorageDirectory(); properties.error_dir = fragment.requireContext().getExternalFilesDir(null); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { FilePickerDialog dialog = new FilePickerDialog(fragment.requireContext(), properties); dialog.setDialogSelectionListener( files -> { ProgressManager.getInstance() .runNonCancelableAsync( () -> { for (String file : files) { try { FileUtils.copyFileToDirectory(new File(file), currentDir); } catch (IOException ioException) { ProgressManager.getInstance() .runLater( () -> { if (fragment.isDetached() || fragment.getContext() == null) { return; } AndroidUtilities.showSimpleAlert( e.getDataContext(), R.string.error, ioException.getLocalizedMessage()); }); } } ProgressManager.getInstance() .runLater( () -> { if (fragment.isDetached() || fragment.getContext() == null) { return; } refreshTreeView(currentNode, fragment.getTreeView()); }); }); }); dialog.show(); } else { Project project = e.getData(CommonDataKeys.PROJECT); if (project != null) { fragment.importFile(project.getRootFile(), currentDir); } } } }
4,066
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CreateLayoutAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/xml/CreateLayoutAction.java
package com.tyron.code.ui.file.action.xml; import android.content.Context; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.code.template.CodeTemplate; import com.tyron.code.template.xml.LayoutTemplate; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.RegexReason; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.dialog.CreateClassDialogFragment; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.code.ui.project.ProjectManager; import com.tyron.code.util.ProjectUtils; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import org.codeassist.unofficial.R; public class CreateLayoutAction extends FileAction { @Override public String getTitle(Context context) { return context.getString(R.string.menu_new_layout); } @Override public boolean isApplicable(File file) { if (file.isDirectory()) { return ProjectUtils.isResourceXMLDir(file) && file.getName().startsWith("layout"); } return false; } @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = e.getRequiredData(CommonFileKeys.TREE_NODE); CreateClassDialogFragment dialogFragment = CreateClassDialogFragment.newInstance( getTemplates(), Collections.singletonList( new RegexReason( "^[a-z0-9_]+$", fragment.getString(R.string.error_resource_name_restriction)))); dialogFragment.show(fragment.getChildFragmentManager(), null); dialogFragment.setOnClassCreatedListener( (className, template) -> { try { File createdFile = ProjectManager.createFile(currentNode.getContent().getFile(), className, template); if (createdFile == null) { throw new IOException(fragment.getString(R.string.error_file_creation)); } TreeNode<TreeFile> newNode = new TreeNode<>(TreeFile.fromFile(createdFile), currentNode.getLevel() + 1); treeView.addNode(currentNode, newNode); treeView.refreshTreeView(); FileEditorManagerImpl.getInstance() .openFile( fragment.requireContext(), createdFile, fileEditor -> fragment.getMainViewModel().openFile(fileEditor)); } catch (IOException exception) { new MaterialAlertDialogBuilder(fragment.requireContext()) .setMessage(exception.getMessage()) .setPositiveButton(android.R.string.ok, null) .setTitle(R.string.error) .show(); } }); } private List<CodeTemplate> getTemplates() { return Collections.singletonList(new LayoutTemplate()); } }
3,375
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CreateAndroidClassAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/android/CreateAndroidClassAction.java
package com.tyron.code.ui.file.action.android; import android.content.Context; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.api.AndroidModule; import com.tyron.builder.project.api.Module; import com.tyron.code.template.android.ActivityTemplate; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.java.CreateClassAction; import com.tyron.code.ui.file.dialog.CreateClassDialogFragment; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.TreeUtil; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.code.ui.project.ProjectManager; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import java.io.IOException; import java.util.Collections; public class CreateAndroidClassAction extends CreateClassAction { @Override public String getTitle(Context context) { return "Android Class"; } @Override public void actionPerformed(@NonNull AnActionEvent e) { TreeFileManagerFragment treeFragment = (TreeFileManagerFragment) e.getData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = treeFragment.getTreeView(); TreeNode<TreeFile> treeNode = e.getData(CommonFileKeys.TREE_NODE); CreateClassDialogFragment fragment = CreateClassDialogFragment.newInstance( Collections.singletonList(new ActivityTemplate()), Collections.emptyList()); fragment.show(treeFragment.getChildFragmentManager(), null); fragment.setOnClassCreatedListener( (className, template) -> { try { File currentFile = treeNode.getContent().getFile(); if (currentFile == null) { throw new IOException("Unable to create class"); } File createdFile = ProjectManager.createClass(currentFile, className, template); TreeUtil.updateNode(treeNode.getParent()); treeView.refreshTreeView(); FileEditorManagerImpl.getInstance() .openFile( treeFragment.requireContext(), createdFile, fileEditor -> treeFragment.getMainViewModel().openFile(fileEditor)); Module currentModule = ProjectManager.getInstance() .getCurrentProject() .getModule(treeNode.getContent().getFile()); if (currentModule instanceof AndroidModule) { ((AndroidModule) currentModule).addJavaFile(createdFile); } } catch (IOException exception) { new MaterialAlertDialogBuilder(treeFragment.requireContext()) .setMessage(exception.getMessage()) .setPositiveButton(android.R.string.ok, null) .setTitle("Error") .show(); } }); } }
3,092
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GitResetChangesAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/git/GitResetChangesAction.java
package com.tyron.code.ui.file.action.git; import android.content.Context; import androidx.annotation.NonNull; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.Project; import com.tyron.code.tasks.git.ResetChangesTask; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class GitResetChangesAction extends FileAction { public static final String ID = "fileManagerGitResetChangesAction"; private Project project; private Context context; @Override public String getTitle(Context context) { return context.getString(R.string.menu_git_reset_changes); } @Override public boolean isApplicable(File file) { return true; } @Override public void actionPerformed(@NonNull AnActionEvent e) { project = e.getData(CommonDataKeys.PROJECT); if (project == null) { return; } context = e.getData(CommonDataKeys.CONTEXT); TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = e.getRequiredData(CommonFileKeys.TREE_NODE); File rootProject = project.getRootFile(); File currentFile = currentNode.getValue().getFile(); String path = currentFile .getAbsolutePath() .substring((rootProject.getAbsolutePath() + "/app").lastIndexOf("/") + 1); ResetChangesTask.INSTANCE.reset(project, path, context); } }
1,809
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GitAddToStageAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/git/GitAddToStageAction.java
package com.tyron.code.ui.file.action.git; import android.content.Context; import androidx.annotation.NonNull; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.Project; import com.tyron.code.tasks.git.AddToStageTask; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class GitAddToStageAction extends FileAction { public static final String ID = "fileManagerGitAddToStageAction"; private Project project; private Context context; @Override public String getTitle(Context context) { return context.getString(R.string.menu_git_add_to_stage); } @Override public boolean isApplicable(File file) { return true; } @Override public void actionPerformed(@NonNull AnActionEvent e) { project = e.getData(CommonDataKeys.PROJECT); if (project == null) { return; } context = e.getData(CommonDataKeys.CONTEXT); TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = e.getRequiredData(CommonFileKeys.TREE_NODE); File rootProject = project.getRootFile(); File currentFile = currentNode.getValue().getFile(); String path = currentFile .getAbsolutePath() .substring((rootProject.getAbsolutePath() + "/app").lastIndexOf("/") + 1); String name = currentFile.getName(); AddToStageTask.INSTANCE.add(project, path, name, context); } }
1,846
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GitRemoveFromIndexForceAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/git/GitRemoveFromIndexForceAction.java
package com.tyron.code.ui.file.action.git; import android.content.Context; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.Project; import com.tyron.code.tasks.git.RemoveFromIndexForceTask; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class GitRemoveFromIndexForceAction extends FileAction { public static final String ID = "fileManagerGitRemoveFromIndexForceAction"; private Project project; private Context context; @Override public String getTitle(Context context) { return context.getString(R.string.menu_git_remove_from_index_force); } @Override public boolean isApplicable(File file) { return true; } @Override public void actionPerformed(@NonNull AnActionEvent e) { project = e.getData(CommonDataKeys.PROJECT); if (project == null) { return; } context = e.getData(CommonDataKeys.CONTEXT); TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = e.getRequiredData(CommonFileKeys.TREE_NODE); File rootProject = project.getRootFile(); File currentFile = currentNode.getValue().getFile(); String path = currentFile .getAbsolutePath() .substring((rootProject.getAbsolutePath() + "/app").lastIndexOf("/") + 1); String name = currentFile.getName(); String message = context.getString(R.string.remove_from_index_force_msg, name); new MaterialAlertDialogBuilder(context) .setTitle(R.string.remove_from_index_force) .setMessage(message) .setPositiveButton( R.string.remove, (d, w) -> RemoveFromIndexForceTask.INSTANCE.remove(project, path, name, context)) .setNegativeButton(android.R.string.cancel, null) .show(); } }
2,329
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GitRemoveFromIndexAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/git/GitRemoveFromIndexAction.java
package com.tyron.code.ui.file.action.git; import android.content.Context; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.Project; import com.tyron.code.tasks.git.RemoveFromIndexTask; import com.tyron.code.ui.file.CommonFileKeys; import com.tyron.code.ui.file.action.FileAction; import com.tyron.code.ui.file.tree.TreeFileManagerFragment; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; import java.io.File; import org.codeassist.unofficial.R; public class GitRemoveFromIndexAction extends FileAction { public static final String ID = "fileManagerGitRemoveFromIndexAction"; private Project project; private Context context; @Override public String getTitle(Context context) { return context.getString(R.string.menu_git_remove_from_index); } @Override public boolean isApplicable(File file) { return true; } @Override public void actionPerformed(@NonNull AnActionEvent e) { project = e.getData(CommonDataKeys.PROJECT); if (project == null) { return; } context = e.getData(CommonDataKeys.CONTEXT); TreeFileManagerFragment fragment = (TreeFileManagerFragment) e.getRequiredData(CommonDataKeys.FRAGMENT); TreeView<TreeFile> treeView = fragment.getTreeView(); TreeNode<TreeFile> currentNode = e.getRequiredData(CommonFileKeys.TREE_NODE); File rootProject = project.getRootFile(); File currentFile = currentNode.getValue().getFile(); String path = currentFile .getAbsolutePath() .substring((rootProject.getAbsolutePath() + "/app").lastIndexOf("/") + 1); String name = currentFile.getName(); String message = context.getString(R.string.remove_from_index_msg, name); new MaterialAlertDialogBuilder(context) .setTitle(R.string.remove_from_index) .setMessage(message) .setPositiveButton( R.string.remove, (d, w) -> RemoveFromIndexTask.INSTANCE.remove(project, path, name, context)) .setNegativeButton(android.R.string.cancel, null) .show(); } }
2,291
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GitCommitAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/action/git/GitCommitAction.java
package com.tyron.code.ui.file.action.git; import android.content.Context; import androidx.annotation.NonNull; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.builder.project.Project; import com.tyron.code.tasks.git.GitCommitTask; import com.tyron.code.ui.file.action.FileAction; import java.io.File; import org.codeassist.unofficial.R; public class GitCommitAction extends FileAction { public static final String ID = "fileManagerGitCommitAction"; private Project project; private Context context; @Override public String getTitle(Context context) { return context.getString(R.string.menu_commit); } @Override public boolean isApplicable(File file) { return true; } @Override public void actionPerformed(@NonNull AnActionEvent e) { project = e.getData(CommonDataKeys.PROJECT); if (project == null) { return; } context = e.getData(CommonDataKeys.CONTEXT); GitCommitTask.INSTANCE.commit(project, context); } }
1,023
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileManagerFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/dialog/FileManagerFragment.java
package com.tyron.code.ui.file.dialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import androidx.activity.OnBackPressedCallback; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.file.FileManagerAdapter; import com.tyron.code.ui.main.MainFragment; import java.io.File; import java.util.Objects; import org.codeassist.unofficial.R; @SuppressWarnings("FieldCanBeLocal") public class FileManagerFragment extends Fragment { public static FileManagerFragment newInstance(File file) { FileManagerFragment fragment = new FileManagerFragment(); Bundle args = new Bundle(); args.putString("path", file.getAbsolutePath()); fragment.setArguments(args); return fragment; } OnBackPressedCallback callback = new OnBackPressedCallback(false) { @Override public void handleOnBackPressed() { if (!mCurrentFile.equals(mRootFile)) { mAdapter.submitFile(Objects.requireNonNull(mCurrentFile.getParentFile())); check(mCurrentFile.getParentFile()); } } }; private File mRootFile; private File mCurrentFile; private LinearLayout mRoot; private RecyclerView mListView; private LinearLayoutManager mLayoutManager; private FileManagerAdapter mAdapter; public FileManagerFragment() {} public void disableBackListener() { callback.setEnabled(false); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); assert getArguments() != null; mRootFile = new File(getArguments().getString("path")); if (savedInstanceState != null) { mCurrentFile = new File(savedInstanceState.getString("currentFile"), mRootFile.getAbsolutePath()); } else { mCurrentFile = mRootFile; } } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRoot = (LinearLayout) inflater.inflate(R.layout.file_manager_fragment, container, false); mLayoutManager = new LinearLayoutManager(requireContext()); mAdapter = new FileManagerAdapter(); mListView = mRoot.findViewById(R.id.listView); mListView.setLayoutManager(mLayoutManager); mListView.setAdapter(mAdapter); requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), callback); return mRoot; } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mAdapter.submitFile(mCurrentFile); mAdapter.setOnItemClickListener( (file, position) -> { if (position == 0) { if (!mCurrentFile.equals(mRootFile)) { mAdapter.submitFile(Objects.requireNonNull(mCurrentFile.getParentFile())); check(mCurrentFile.getParentFile()); } return; } if (file.isFile()) { openFile(file); } else if (file.isDirectory()) { mAdapter.submitFile(file); check(file); } }); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("currentDir", mCurrentFile); } private void openFile(File file) { Fragment parent = getParentFragment(); if (parent != null) { if (parent instanceof MainFragment) { ((MainFragment) parent) .openFile( FileEditorManagerImpl.getInstance().openFile(requireContext(), file, true)[0]); } } } /** * Checks if the current file is equal to the root file if so, it disables the * OnBackPressedCallback */ private void check(File currentFile) { mCurrentFile = currentFile; callback.setEnabled(!currentFile.getAbsolutePath().equals(mRootFile.getAbsolutePath())); } }
4,184
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CreateClassDialogFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/dialog/CreateClassDialogFragment.java
package com.tyron.code.ui.file.dialog; import android.app.Dialog; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatAutoCompleteTextView; import androidx.fragment.app.DialogFragment; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.tyron.code.template.CodeTemplate; import com.tyron.code.template.java.JavaClassTemplate; import com.tyron.code.ui.file.RegexReason; import com.tyron.common.util.SingleTextWatcher; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.lang.model.SourceVersion; import org.codeassist.unofficial.R; public class CreateClassDialogFragment extends DialogFragment { public static CreateClassDialogFragment newInstance( List<CodeTemplate> templates, List<RegexReason> regex) { CreateClassDialogFragment fragment = new CreateClassDialogFragment(); Bundle args = new Bundle(); args.putParcelableArrayList("regex", new ArrayList<>(regex)); args.putParcelableArrayList("templates", new ArrayList<>(templates)); fragment.setArguments(args); return fragment; } public interface OnClassCreatedListener { void onClassCreated(String className, CodeTemplate template); } private List<CodeTemplate> mTemplates; private OnClassCreatedListener mListener; private TextInputLayout mClassNameLayout; private TextInputEditText mClassNameEditText; private AppCompatAutoCompleteTextView mClassTypeTextView; public void setOnClassCreatedListener(OnClassCreatedListener listener) { mListener = listener; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTemplates = getTemplates(); } @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext()); builder.setTitle(R.string.dialog_create_class_title); // noinspection InflateParams View view = getLayoutInflater().inflate(R.layout.create_class_dialog, null); mClassNameLayout = view.findViewById(R.id.til_class_name); mClassNameEditText = view.findViewById(R.id.et_class_name); ArrayAdapter<CodeTemplate> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1, mTemplates); mClassTypeTextView = view.findViewById(R.id.et_class_type); mClassTypeTextView.setAdapter(adapter); mClassTypeTextView.setText(mTemplates.get(0).getName(), false); builder.setView(view); builder.setPositiveButton( R.string.create_class_dialog_positive, ((dialogInterface, i) -> { if (mListener != null) { mListener.onClassCreated( String.valueOf(mClassNameEditText.getText()), getCurrentTemplate()); } })); builder.setNegativeButton(android.R.string.cancel, null); AlertDialog dialog = builder.create(); dialog.setOnShowListener( dialogInterface -> { final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); positiveButton.setEnabled(false); mClassNameEditText.addTextChangedListener( new SingleTextWatcher() { @Override public void afterTextChanged(Editable editable) { String name = editable.toString(); if (getCurrentTemplate() instanceof JavaClassTemplate) { if (SourceVersion.isName(name)) { mClassNameLayout.setErrorEnabled(false); positiveButton.setEnabled(true); } else { positiveButton.setEnabled(false); mClassNameLayout.setError( getString(R.string.create_class_dialog_invalid_name)); } } else { if (isValid(name)) { mClassNameLayout.setErrorEnabled(false); positiveButton.setEnabled(true); } else { positiveButton.setEnabled(false); } } } }); }); return dialog; } private CodeTemplate getCurrentTemplate() { String name = String.valueOf(mClassTypeTextView.getText()); return mTemplates.stream() .filter(temp -> temp.getName().equals(name)) .findAny() .orElse(new JavaClassTemplate()); } private List<CodeTemplate> getTemplates() { return requireArguments().getParcelableArrayList("templates"); } private boolean isValid(String string) { List<RegexReason> regex = requireArguments().getParcelableArrayList("regex"); for (RegexReason s : regex) { Pattern pattern = Pattern.compile(s.getRegexString()); Matcher matcher = pattern.matcher(string); if (!matcher.find()) { mClassNameLayout.setError(s.getReason()); return false; } } return true; } }
5,431
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
RefreshRootEvent.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/file/event/RefreshRootEvent.java
package com.tyron.code.ui.file.event; import androidx.annotation.NonNull; import com.tyron.code.event.Event; import java.io.File; /** Used to notify the file manager that its root needs to be refreshed */ public class RefreshRootEvent extends Event { private final File mRoot; public RefreshRootEvent(@NonNull File root) { mRoot = root; } @NonNull public File getRoot() { return mRoot; } }
415
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SettingsActivity.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/settings/SettingsActivity.java
package com.tyron.code.ui.settings; import android.os.Bundle; import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import org.codeassist.unofficial.R; public class SettingsActivity extends AppCompatActivity implements PreferenceFragmentCompat.OnPreferenceStartFragmentCallback { private static final String TITLE_TAG = "settingsActivityTitle"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings_activity); if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .replace(R.id.settings, new SettingsFragment()) .commit(); } else { setTitle(savedInstanceState.getCharSequence(TITLE_TAG)); } getSupportFragmentManager() .addOnBackStackChangedListener( () -> { if (getSupportFragmentManager().getBackStackEntryCount() == 0) { setTitle(R.string.title_activity_settings); } }); setSupportActionBar(findViewById(R.id.toolbar)); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); // Save current activity title so we can set it again after a configuration change outState.putCharSequence(TITLE_TAG, getTitle()); } @Override public boolean onSupportNavigateUp() { if (getSupportFragmentManager().popBackStackImmediate()) { return true; } return super.onSupportNavigateUp(); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == android.R.id.home) { FragmentManager manager = getSupportFragmentManager(); if (!manager.popBackStackImmediate()) { finish(); } return true; } return super.onOptionsItemSelected(item); } @Override public boolean onPreferenceStartFragment(PreferenceFragmentCompat caller, Preference pref) { // Instantiate the new Fragment final Bundle args = pref.getExtras(); final Fragment fragment = getSupportFragmentManager() .getFragmentFactory() .instantiate(getClassLoader(), pref.getFragment()); fragment.setArguments(args); fragment.setTargetFragment(caller, 0); // Replace the existing Fragment with the new Fragment getSupportFragmentManager() .beginTransaction() .replace(R.id.settings, fragment) .addToBackStack(null) .commit(); setTitle(pref.getTitle()); return true; } }
2,978
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ProjectSettingsFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/settings/ProjectSettingsFragment.java
package com.tyron.code.ui.settings; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.preference.PreferenceFragmentCompat; import com.google.android.material.transition.MaterialSharedAxis; import org.codeassist.unofficial.R; public class ProjectSettingsFragment extends PreferenceFragmentCompat { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setEnterTransition(new MaterialSharedAxis(MaterialSharedAxis.X, false)); setExitTransition(new MaterialSharedAxis(MaterialSharedAxis.X, true)); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.project_preferences, rootKey); } }
766
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SettingsFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/settings/SettingsFragment.java
package com.tyron.code.ui.settings; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.preference.PreferenceFragmentCompat; import com.google.android.material.transition.MaterialSharedAxis; import org.codeassist.unofficial.R; public class SettingsFragment extends PreferenceFragmentCompat { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setEnterTransition(new MaterialSharedAxis(MaterialSharedAxis.X, false)); setExitTransition(new MaterialSharedAxis(MaterialSharedAxis.X, true)); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.root_preferences, rootKey); } }
756
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ApplicationSettingsFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/settings/ApplicationSettingsFragment.java
package com.tyron.code.ui.settings; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import androidx.appcompat.app.AppCompatDelegate; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceManager; import com.tyron.common.SharedPreferenceKeys; import org.codeassist.unofficial.R; public class ApplicationSettingsFragment extends PreferenceFragmentCompat { public static class ThemeProvider { private final Context context; public ThemeProvider(Context context) { this.context = context; } public int getThemeFromPreferences() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String selectedTheme = preferences.getString("theme", "default"); return getTheme(selectedTheme); } public String getDescriptionForTheme(String selectedTheme) { switch (selectedTheme) { case "light": return context.getString(R.string.settings_theme_value_light); case "night": return context.getString(R.string.settings_theme_value_dark); default: return context.getString(R.string.settings_theme_value_default); } } private int getTheme(String selectedTheme) { switch (selectedTheme) { case "light": return AppCompatDelegate.MODE_NIGHT_NO; case "dark": return AppCompatDelegate.MODE_NIGHT_YES; default: return AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM; } } } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.application_preferences, rootKey); Preference theme = findPreference(SharedPreferenceKeys.THEME); assert theme != null; theme.setOnPreferenceChangeListener( (preference, newValue) -> { if (newValue instanceof String) { ThemeProvider provider = new ThemeProvider(requireContext()); int newTheme = provider.getTheme((String) newValue); AppCompatDelegate.setDefaultNightMode(newTheme); theme.setSummaryProvider( p -> provider.getDescriptionForTheme(String.valueOf(newValue))); return true; } return false; }); } }
2,383
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
EditorSettingsFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/settings/EditorSettingsFragment.java
package com.tyron.code.ui.settings; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.widget.Button; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.content.ContextCompat; import androidx.preference.EditTextPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputLayout; import com.google.android.material.transition.MaterialSharedAxis; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.tyron.common.SharedPreferenceKeys; import com.tyron.common.util.SingleTextWatcher; import com.tyron.completion.progress.ProgressManager; import io.github.rosemoe.sora.langs.textmate.theme.TextMateColorScheme; import io.github.rosemoe.sora.textmate.core.internal.theme.reader.ThemeReader; import io.github.rosemoe.sora.textmate.core.theme.IRawTheme; import io.github.rosemoe.sora2.text.EditorUtil; import java.io.File; import java.util.Objects; import org.apache.commons.io.FileUtils; import org.codeassist.unofficial.R; public class EditorSettingsFragment extends PreferenceFragmentCompat { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setEnterTransition(new MaterialSharedAxis(MaterialSharedAxis.X, false)); setExitTransition(new MaterialSharedAxis(MaterialSharedAxis.X, true)); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.editor_preferences, rootKey); EditTextPreference fontSize = findPreference(SharedPreferenceKeys.FONT_SIZE); if (fontSize != null) { fontSize.setOnBindEditTextListener( editText -> editText.setInputType(InputType.TYPE_CLASS_NUMBER)); } Preference scheme = findPreference(SharedPreferenceKeys.SCHEME); assert scheme != null; scheme.setOnPreferenceClickListener( preference -> { SharedPreferences pref = preference.getSharedPreferences(); String path = pref.getString("scheme", ""); File currentTheme = new File(path); AlertDialog dialog = new MaterialAlertDialogBuilder(requireContext()) .setView(R.layout.base_textinput_layout) .setTitle(R.string.change_scheme_dialog_title) .setNeutralButton( R.string.defaultString, (d, w) -> { pref.edit().putString(SharedPreferenceKeys.SCHEME, null).apply(); preference.callChangeListener(null); }) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.save, null) .create(); dialog.setOnShowListener( d -> { final Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE); TextInputLayout layout = dialog.findViewById(R.id.textinput_layout); layout.setHint(R.string.set_scheme_file_path); EditText editText = Objects.requireNonNull(layout).getEditText(); assert editText != null; editText.setText(currentTheme.getAbsolutePath()); editText.addTextChangedListener( new SingleTextWatcher() { @Override public void afterTextChanged(Editable editable) { File file = new File(editable.toString()); boolean enabled = file.exists() && file.canRead() && file.isFile(); button.setEnabled(enabled); } }); button.setOnClickListener( v -> { File file = new File(editText.getText().toString()); ListenableFuture<TextMateColorScheme> future = getColorScheme(file); Futures.addCallback( future, new FutureCallback<TextMateColorScheme>() { @Override public void onSuccess(@Nullable TextMateColorScheme result) { pref.edit() .putString(SharedPreferenceKeys.SCHEME, file.getAbsolutePath()) .apply(); preference.callChangeListener(file.getAbsolutePath()); d.dismiss(); } @Override public void onFailure(@NonNull Throwable t) { d.dismiss(); new MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.error) .setMessage(t.getMessage()) .setPositiveButton(android.R.string.ok, null) .setNegativeButton(android.R.string.cancel, null) .show(); } }, ContextCompat.getMainExecutor(requireContext())); }); }); dialog.show(); return true; }); } public static ListenableFuture<TextMateColorScheme> getColorScheme(@NonNull File file) { return ProgressManager.getInstance() .computeNonCancelableAsync( () -> { IRawTheme rawTheme = ThemeReader.readThemeSync( file.getAbsolutePath(), FileUtils.openInputStream(file)); return Futures.immediateFuture(EditorUtil.createTheme(rawTheme)); }); } }
6,251
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GitSettingsFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/settings/GitSettingsFragment.java
package com.tyron.code.ui.settings; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.transition.MaterialSharedAxis; import com.tyron.common.SharedPreferenceKeys; import org.codeassist.unofficial.R; import org.codeassist.unofficial.databinding.BaseTextinputLayoutBinding; public class GitSettingsFragment extends PreferenceFragmentCompat { private BaseTextinputLayoutBinding binding; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setEnterTransition(new MaterialSharedAxis(MaterialSharedAxis.X, false)); setExitTransition(new MaterialSharedAxis(MaterialSharedAxis.X, true)); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.git_preferences, rootKey); } @Override public boolean onPreferenceTreeClick(Preference preference) { String key = preference.getKey(); SharedPreferences pref = preference.getSharedPreferences(); String user_name = pref.getString("user_name", ""); String user_email = pref.getString("user_email", ""); binding = BaseTextinputLayoutBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); switch (key) { case SharedPreferenceKeys.GIT_USER_NAME: AlertDialog dialog = new MaterialAlertDialogBuilder(requireContext()) .setView(view) .setTitle(R.string.enter_full_name) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, null) .create(); dialog.setOnShowListener( d -> { final Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE); binding.textinputLayout.setHint(R.string.git_user_name_title); EditText editText = binding.textinputLayout.getEditText(); editText.setText(user_name); button.setOnClickListener( v -> { String name = binding.textinputLayout.getEditText().getText().toString(); pref.edit().putString(SharedPreferenceKeys.GIT_USER_NAME, name).apply(); preference.callChangeListener(name); d.dismiss(); }); }); dialog.show(); return true; case SharedPreferenceKeys.GIT_USER_EMAIL: AlertDialog dialog1 = new MaterialAlertDialogBuilder(requireContext()) .setView(view) .setTitle(R.string.enter_email) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, null) .create(); dialog1.setOnShowListener( d -> { final Button button = dialog1.getButton(DialogInterface.BUTTON_POSITIVE); binding.textinputLayout.setHint(R.string.git_user_email_title); EditText editText = binding.textinputLayout.getEditText(); editText.setText(user_email); button.setOnClickListener( v -> { String email = binding.textinputLayout.getEditText().getText().toString(); pref.edit().putString(SharedPreferenceKeys.GIT_USER_EMAIL, email).apply(); preference.callChangeListener(email); d.dismiss(); }); }); dialog1.show(); return true; } return super.onPreferenceTreeClick(preference); } }
4,013
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AboutUsFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/settings/AboutUsFragment.java
package com.tyron.code.ui.settings; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import androidx.annotation.DrawableRes; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import com.danielstone.materialaboutlibrary.ConvenienceBuilder; import com.danielstone.materialaboutlibrary.MaterialAboutFragment; import com.danielstone.materialaboutlibrary.items.MaterialAboutActionItem; import com.danielstone.materialaboutlibrary.model.MaterialAboutCard; import com.danielstone.materialaboutlibrary.model.MaterialAboutList; import com.danielstone.materialaboutlibrary.util.OpenSourceLicense; import com.google.android.material.transition.MaterialSharedAxis; import org.codeassist.unofficial.R; public class AboutUsFragment extends MaterialAboutFragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setEnterTransition(new MaterialSharedAxis(MaterialSharedAxis.X, false)); setExitTransition(new MaterialSharedAxis(MaterialSharedAxis.X, true)); } @Override protected MaterialAboutList getMaterialAboutList(Context context) { MaterialAboutCard appCard = new MaterialAboutCard.Builder() .addItem(ConvenienceBuilder.createAppTitleItem(context)) .addItem( new MaterialAboutActionItem.Builder().subText(R.string.app_description).build()) .addItem( ConvenienceBuilder.createVersionActionItem( context, getDrawable(R.drawable.ic_round_info_24), getString(R.string.app_version), true)) .addItem( ConvenienceBuilder.createEmailItem( context, getDrawable(R.drawable.ic_round_email_24), getString(R.string.settings_about_us_title), false, "deenbandhunetam488@gmail.com", "")) .addItem( ConvenienceBuilder.createWebsiteActionItem( context, getDrawable(R.drawable.ic_baseline_open_in_new_24), getString(R.string.app_source_title), false, Uri.parse("https://github.com/Deenu488/CodeAssist-Unofficial"))) .addItem( ConvenienceBuilder.createRateActionItem( context, getDrawable(R.drawable.ic_round_star_rate_24), getString(R.string.rate_us), null)) .build(); MaterialAboutCard communityCard = new MaterialAboutCard.Builder() .title(R.string.community) .addItem( ConvenienceBuilder.createWebsiteActionItem( context, getDrawable(R.drawable.ic_icons8_discord), "Discord", false, Uri.parse("https://discord.gg/pffnyE6prs"))) .addItem( ConvenienceBuilder.createWebsiteActionItem( context, getDrawable(R.drawable.ic_icons8_telegram_app), "Telegram", false, Uri.parse("https://t.me/codeassist_app"))) .build(); MaterialAboutCard licenseCard = ConvenienceBuilder.createLicenseCard( context, getDrawable(R.drawable.ic_baseline_menu_book_24), getString(R.string.app_name), "2024", "Tyron, Deenu", OpenSourceLicense.GNU_GPL_3); return new MaterialAboutList.Builder() .addCard(appCard) .addCard(communityCard) .addCard(licenseCard) .build(); } private Drawable getDrawable(@DrawableRes int drawable) { return ResourcesCompat.getDrawable( requireContext().getResources(), drawable, requireContext().getTheme()); } }
4,072
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BuildSettingsFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/settings/BuildSettingsFragment.java
package com.tyron.code.ui.settings; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.preference.PreferenceFragmentCompat; import com.google.android.material.transition.MaterialSharedAxis; import org.codeassist.unofficial.R; public class BuildSettingsFragment extends PreferenceFragmentCompat { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setEnterTransition(new MaterialSharedAxis(MaterialSharedAxis.X, false)); setExitTransition(new MaterialSharedAxis(MaterialSharedAxis.X, true)); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.build_preferences, rootKey); } }
762
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SshKeys.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/ssh/SshKeys.java
package com.tyron.code.ui.ssh; import java.io.File; public class SshKeys { private final File mRoot; public SshKeys(File root) { mRoot = root; } public File getRootFile() { return mRoot; } }
214
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SshKeyManagerFragment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/ssh/SshKeyManagerFragment.java
package com.tyron.code.ui.ssh; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.text.Editable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.Toolbar; import androidx.core.view.ViewCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.transition.TransitionManager; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputLayout; import com.google.android.material.transition.MaterialFade; import com.jcraft.jsch.JSch; import com.jcraft.jsch.KeyPair; import com.tyron.code.ApplicationLoader; import com.tyron.code.ui.ssh.adapter.SshKeyManagerAdapter; import com.tyron.code.util.UiUtilsKt; import com.tyron.common.SharedPreferenceKeys; import com.tyron.common.util.AndroidUtilities; import com.tyron.completion.progress.ProgressManager; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.Executors; import org.apache.commons.io.FileUtils; import org.codeassist.unofficial.R; public class SshKeyManagerFragment extends Fragment { public static final String TAG = SshKeyManagerFragment.class.getSimpleName(); private RecyclerView mRecyclerView; private SshKeyManagerAdapter mAdapter; private SharedPreferences mPreferences = ApplicationLoader.getDefaultPreferences(); private File sshDir; private File privateKey; private File publicKey; public static SshKeyManagerFragment newInstance() { SshKeyManagerFragment fragment = new SshKeyManagerFragment(); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView( @NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.ssh_key_manager_fragment, container, false); view.setClickable(true); Toolbar toolbar = view.findViewById(R.id.toolbar); toolbar.setNavigationOnClickListener(v -> getParentFragmentManager().popBackStack()); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { Toolbar toolbar = view.findViewById(R.id.toolbar); toolbar.setOnMenuItemClickListener(menu -> getParentFragmentManager().popBackStackImmediate()); View fab = view.findViewById(R.id.fab_add_ssh_key); UiUtilsKt.addSystemWindowInsetToMargin(fab, false, false, false, true); ViewCompat.requestApplyInsets(fab); mAdapter = new SshKeyManagerAdapter(); mAdapter.OnSshKeysLongClickedListener(this::inflateSshKeysMenus); mRecyclerView = view.findViewById(R.id.ssh_keys_recycler); mRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext())); mRecyclerView.setAdapter(mAdapter); loadSshKeys(); fab.setOnClickListener( v -> { LayoutInflater inflater = (LayoutInflater) requireContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View vie = inflater.inflate(R.layout.base_textinput_layout, null); TextInputLayout layout = vie.findViewById(R.id.textinput_layout); layout.setHint(R.string.keyName); final Editable keyName = layout.getEditText().getText(); new MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.generateKey) .setView(vie) .setPositiveButton( R.string.generate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dia, int which) { generateSshKeys(keyName.toString()); } }) .setNegativeButton(android.R.string.cancel, null) .show(); }); } private void generateSshKeys(String keyName) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { sshDir = new File(requireContext().getExternalFilesDir("/.ssh").getAbsolutePath()); } else { sshDir = new File(Environment.getExternalStorageDirectory() + "/.ssh"); } if (sshDir.exists()) { } else { sshDir.mkdirs(); } privateKey = new File(sshDir.getAbsolutePath(), keyName + ".key"); publicKey = new File(sshDir.getAbsolutePath(), keyName + ".pub"); if (privateKey.exists()) { Toast toast = Toast.makeText(requireContext(), R.string.keyExists, Toast.LENGTH_LONG); toast.show(); return; } if (keyName.isEmpty()) { Toast toast = Toast.makeText(requireContext(), R.string.keyEmpty, Toast.LENGTH_LONG); toast.show(); return; } else { try { JSch jsch = new JSch(); KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 4096); keyPair.writePrivateKey(new FileOutputStream(privateKey)); keyPair.writePublicKey(new FileOutputStream(publicKey), "codeassist"); keyPair.dispose(); } catch (Exception e) { privateKey.delete(); if (getActivity() != null) { requireActivity() .runOnUiThread( () -> AndroidUtilities.showSimpleAlert( requireContext(), getString(R.string.error), e.getMessage())); } } mPreferences .edit() .putString(SharedPreferenceKeys.SSH_KEY_NAME, privateKey.getName()) .apply(); loadSshKeys(); Toast toast = Toast.makeText(requireContext(), R.string.keyLoaded, Toast.LENGTH_LONG); toast.show(); } } private void loadSshKeys() { toggleLoading(true); Executors.newSingleThreadExecutor() .execute( () -> { String path; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { path = requireContext().getExternalFilesDir("/.ssh").getAbsolutePath(); } else { path = Environment.getExternalStorageDirectory() + "/.ssh"; } File sshKeysDir = new File(path); if (sshKeysDir.exists()) { } else { sshKeysDir.mkdirs(); } File[] files = sshKeysDir.listFiles(File::isFile); List<SshKeys> sshKeys = new ArrayList<>(); if (files != null) { Arrays.sort(files, Comparator.comparingLong(File::lastModified)); for (File file : files) { if (file.exists()) { SshKeys sshkeys = new SshKeys(new File(file.getAbsolutePath().replaceAll("%20", " "))); if (sshkeys.getRootFile().getName().endsWith(".key")) { sshKeys.add(sshkeys); } if (sshkeys.getRootFile().getName().endsWith(".pub")) { sshKeys.add(sshkeys); } } } } if (getActivity() != null) { requireActivity() .runOnUiThread( () -> { toggleLoading(false); ProgressManager.getInstance() .runLater( () -> { mAdapter.submitList(sshKeys); toggleNullProject(sshKeys); }, 300); }); } }); } private void toggleNullProject(List<SshKeys> sshkeys) { ProgressManager.getInstance() .runLater( () -> { if (getActivity() == null || isDetached()) { return; } View view = getView(); if (view == null) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { sshDir = new File(requireContext().getExternalFilesDir("/.ssh").getAbsolutePath()); } else { sshDir = new File(Environment.getExternalStorageDirectory() + "/.ssh"); } View recycler = view.findViewById(R.id.ssh_keys_recycler); View empty = view.findViewById(R.id.empty_ssh_keys); View fab = view.findViewById(R.id.fab_add_ssh_key); TextView current_key = view.findViewById(R.id.ssh_key_path); fab.setVisibility(View.GONE); String keyName = mPreferences.getString(SharedPreferenceKeys.SSH_KEY_NAME, ""); TransitionManager.beginDelayedTransition( (ViewGroup) recycler.getParent(), new MaterialFade()); if (sshkeys.size() == 0) { recycler.setVisibility(View.GONE); empty.setVisibility(View.VISIBLE); fab.setVisibility(View.VISIBLE); current_key.setVisibility(View.VISIBLE); if (keyName.isEmpty()) { current_key.setText("Current Key : Key is not loaded"); } else { current_key.setText( "Current Key : " + sshDir.getAbsolutePath().toString() + "/" + keyName); } } else { recycler.setVisibility(View.VISIBLE); empty.setVisibility(View.GONE); current_key.setVisibility(View.VISIBLE); if (keyName.isEmpty()) { current_key.setText("Current Key : Key is not loaded"); } else { current_key.setText( "Current Key : " + sshDir.getAbsolutePath().toString() + "/" + keyName); } } }, 300); } private void toggleLoading(boolean show) { ProgressManager.getInstance() .runLater( () -> { if (getActivity() == null || isDetached()) { return; } View view = getView(); if (view == null) { return; } View recycler = view.findViewById(R.id.ssh_keys_recycler); View empty = view.findViewById(R.id.empty_container); View empty_ssh_keys = view.findViewById(R.id.empty_ssh_keys); View fab = view.findViewById(R.id.fab_add_ssh_key); TextView current_key = view.findViewById(R.id.ssh_key_path); fab.setVisibility(View.GONE); empty_ssh_keys.setVisibility(View.GONE); TransitionManager.beginDelayedTransition( (ViewGroup) recycler.getParent(), new MaterialFade()); if (show) { recycler.setVisibility(View.GONE); empty.setVisibility(View.VISIBLE); current_key.setVisibility(View.VISIBLE); } else { recycler.setVisibility(View.VISIBLE); empty.setVisibility(View.GONE); current_key.setVisibility(View.VISIBLE); empty.setVisibility(View.GONE); } }, 300); } private boolean inflateSshKeysMenus(View view, final SshKeys sshkeys) { final String privateKeyName = sshkeys.getRootFile().getName(); final String privateKeyPath = sshkeys.getRootFile().getAbsolutePath(); String[] option = {"Delete", "Show Content"}; new MaterialAlertDialogBuilder(requireContext()) .setItems( option, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: String message = getString(R.string.dialog_confirm_delete, sshkeys.getRootFile().getName()); new MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.dialog_delete) .setMessage(message) .setPositiveButton(android.R.string.yes, (d, w) -> deleteSshKeys(sshkeys)) .setNegativeButton(android.R.string.no, null) .show(); break; case 1: try { String content = new String(Files.readAllBytes(Paths.get(privateKeyPath))); requireActivity() .runOnUiThread( () -> { new MaterialAlertDialogBuilder(requireContext()) .setTitle(privateKeyName) .setMessage(content) .setPositiveButton( android.R.string.copy, (d, w) -> copyContent(content)) .show(); }); } catch (IOException e) { if (getActivity() != null) { requireActivity() .runOnUiThread( () -> AndroidUtilities.showSimpleAlert( requireContext(), getString(R.string.error), e.getMessage())); } } break; } } }) .show(); return true; } private void deleteSshKeys(SshKeys sshkeys) { String keyName = mPreferences.getString(SharedPreferenceKeys.SSH_KEY_NAME, ""); Executors.newSingleThreadExecutor() .execute( () -> { try { FileUtils.forceDelete(sshkeys.getRootFile()); if (getActivity() != null) { requireActivity() .runOnUiThread( () -> { Toast toast = Toast.makeText( requireContext(), R.string.delete_success, Toast.LENGTH_LONG); toast.show(); if (keyName.equals(sshkeys.getRootFile().getName())) { mPreferences .edit() .remove(SharedPreferenceKeys.SSH_KEY_NAME) .commit(); } loadSshKeys(); }); } } catch (IOException e) { if (getActivity() != null) { requireActivity() .runOnUiThread( () -> AndroidUtilities.showSimpleAlert( requireContext(), getString(R.string.error), e.getMessage())); } } }); } private void copyContent(String content) { ClipboardManager clipboard = (ClipboardManager) requireContext().getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(content); Toast toast = Toast.makeText(requireContext(), R.string.copied_to_clipboard, Toast.LENGTH_LONG); toast.show(); } }
16,211
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SshKeyManagerAdapter.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/ssh/adapter/SshKeyManagerAdapter.java
package com.tyron.code.ui.ssh.adapter; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.imageview.ShapeableImageView; import com.tyron.code.ui.ssh.SshKeys; import java.util.ArrayList; import java.util.List; import org.codeassist.unofficial.R; public class SshKeyManagerAdapter extends RecyclerView.Adapter<SshKeyManagerAdapter.ViewHolder> { private static final int TYPE_EMPTY = -1; private static final int TYPE_ITEM = 1; private final int limit = 2; public interface OnSshKeysSelectedListener { void onSshKeysSelect(SshKeys sshKeys); } public interface OnSshKeysLongClickedListener { boolean onLongClicked(View view, SshKeys sshKeys); } private final List<SshKeys> mSshKeys = new ArrayList<>(); private OnSshKeysLongClickedListener mLongClickListener; private OnSshKeysSelectedListener mListener; public SshKeyManagerAdapter() {} public void OnSshKeysSelectedListener(OnSshKeysSelectedListener listener) { mListener = listener; } public void OnSshKeysLongClickedListener(OnSshKeysLongClickedListener listener) { mLongClickListener = listener; } public void submitList(@NonNull List<SshKeys> sshKeys) { DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff( new DiffUtil.Callback() { @Override public int getOldListSize() { return mSshKeys.size(); } @Override public int getNewListSize() { return sshKeys.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return mSshKeys.get(oldItemPosition).equals(sshKeys.get(newItemPosition)); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return mSshKeys.get(oldItemPosition).equals(sshKeys.get(newItemPosition)); } }); mSshKeys.clear(); mSshKeys.addAll(sshKeys); diffResult.dispatchUpdatesTo(this); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { FrameLayout root = new FrameLayout(parent.getContext()); root.setLayoutParams( new RecyclerView.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); final ViewHolder holder; if (viewType == TYPE_EMPTY) { holder = new EmptyViewHolder(root); } else { holder = new ItemViewHolder(root); } root.setOnClickListener( v -> { if (mListener != null) { int position = holder.getBindingAdapterPosition(); if (position != RecyclerView.NO_POSITION) { mListener.onSshKeysSelect((mSshKeys.get(position))); } } }); root.setOnLongClickListener( v -> { if (mLongClickListener != null) { int position = holder.getBindingAdapterPosition(); if (position != RecyclerView.NO_POSITION) { return mLongClickListener.onLongClicked(v, mSshKeys.get(position)); } } return false; }); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { if (holder.getItemViewType() == TYPE_ITEM) { ((ItemViewHolder) holder).bind(mSshKeys.get(position)); } } @Override public int getItemCount() { if (mSshKeys.size() > limit) { return limit; } return mSshKeys.size(); } @Override public int getItemViewType(int position) { if (mSshKeys.isEmpty()) { return TYPE_EMPTY; } return TYPE_ITEM; } public static class ViewHolder extends RecyclerView.ViewHolder { public ViewHolder(View view) { super(view); } } private static class ItemViewHolder extends ViewHolder { public ShapeableImageView icon; public TextView title; public ItemViewHolder(FrameLayout view) { super(view); LayoutInflater.from(view.getContext()).inflate(R.layout.ssh_key_item, view); icon = view.findViewById(R.id.icon); title = view.findViewById(R.id.title); } public void bind(SshKeys sshKeys) { if (sshKeys.getRootFile().getName().endsWith(".key")) { icon.setImageResource(R.drawable.ic_key); } else if (sshKeys.getRootFile().getName().endsWith(".pub")) { icon.setImageResource(R.drawable.ic_pub); } title.setText(sshKeys.getRootFile().getName()); } } private static class EmptyViewHolder extends ViewHolder { public final TextView text; public EmptyViewHolder(FrameLayout view) { super(view); text = new TextView(view.getContext()); text.setTextSize(18); text.setText(R.string.ssh_keys_manager_empty); view.addView( text, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER)); } } }
5,398
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SshTransportConfigCallback.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/ssh/callback/SshTransportConfigCallback.java
package com.tyron.code.ui.ssh.callback; import android.content.SharedPreferences; import android.os.Build; import android.os.Environment; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.tyron.code.ApplicationLoader; import com.tyron.common.SharedPreferenceKeys; import java.io.File; import org.eclipse.jgit.api.TransportConfigCallback; import org.eclipse.jgit.transport.JschConfigSessionFactory; import org.eclipse.jgit.transport.OpenSshConfig; import org.eclipse.jgit.transport.SshSessionFactory; import org.eclipse.jgit.transport.SshTransport; import org.eclipse.jgit.transport.Transport; import org.eclipse.jgit.util.FS; public class SshTransportConfigCallback implements TransportConfigCallback { private File sshDir; SharedPreferences sharedPreferences = ApplicationLoader.getDefaultPreferences(); private final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host hc, Session session) { session.setConfig("StrictHostKeyChecking", "no"); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { String keyName = sharedPreferences.getString(SharedPreferenceKeys.SSH_KEY_NAME, ""); JSch jsch = new JSch(); JSch jSch = super.createDefaultJSch(fs); jSch.removeAllIdentity(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { sshDir = new File( ApplicationLoader.applicationContext .getExternalFilesDir("/.ssh") .getAbsolutePath()); } else { sshDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/.ssh"); } if (sshDir.exists()) { } else { sshDir.mkdirs(); } jsch.setKnownHosts(sshDir.toString()); jSch.addIdentity(sshDir.toString() + "/" + keyName, "super-secret-passphrase".getBytes()); return jSch; } }; @Override public void configure(Transport transport) { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(sshSessionFactory); } }
2,322
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ThemeRepository.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/ui/theme/ThemeRepository.java
package com.tyron.code.ui.theme; import com.tyron.common.ApplicationProvider; import io.github.rosemoe.sora.langs.textmate.theme.TextMateColorScheme; import io.github.rosemoe.sora2.text.EditorUtil; import java.util.HashMap; import java.util.Map; public class ThemeRepository { public static final String DEFAULT_LIGHT = "code_assist_default_light"; public static final String DEFAULT_NIGHT = "code_assist_default_night"; private static final Map<String, TextMateColorScheme> sSchemeCache = new HashMap<>(); public static void putColorScheme(String key, TextMateColorScheme scheme) { sSchemeCache.put(key, scheme); } public static TextMateColorScheme getColorScheme(String key) { return sSchemeCache.get(key); } public static TextMateColorScheme getDefaultScheme(boolean light) { return EditorUtil.getDefaultColorScheme(ApplicationProvider.getApplicationContext(), light); } }
913
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompilerService.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/service/CompilerService.java
package com.tyron.code.service; import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.util.Log; import androidx.annotation.Nullable; import androidx.core.app.NotificationChannelCompat; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.tyron.builder.compiler.AndroidAppBuilder; import com.tyron.builder.compiler.AndroidAppBundleBuilder; import com.tyron.builder.compiler.ApkBuilder; import com.tyron.builder.compiler.BuildType; import com.tyron.builder.compiler.Builder; import com.tyron.builder.compiler.ProjectBuilder; import com.tyron.builder.log.ILogger; import com.tyron.builder.model.DiagnosticWrapper; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import com.tyron.builder.project.api.Module; import com.tyron.code.util.ApkInstaller; import com.tyron.completion.progress.ProgressIndicator; import com.tyron.completion.progress.ProgressManager; import java.io.File; import java.lang.ref.WeakReference; import org.codeassist.unofficial.BuildConfig; import org.codeassist.unofficial.R; public class CompilerService extends Service { private final Handler mMainHandler = new Handler(Looper.getMainLooper()); private final CompilerBinder mBinder = new CompilerBinder(this); public static class CompilerBinder extends Binder { private final WeakReference<CompilerService> mServiceReference; public CompilerBinder(CompilerService service) { mServiceReference = new WeakReference<>(service); } public CompilerService getCompilerService() { return mServiceReference.get(); } } private Project mProject; private ApkBuilder.OnResultListener onResultListener; private ILogger external; /** Logger that delegates logs to the external logger set */ private final ILogger logger = new ILogger() { @Override public void info(DiagnosticWrapper wrapper) { if (external != null) { external.info(wrapper); } } @Override public void debug(DiagnosticWrapper wrapper) { if (external != null) { external.debug(wrapper); } } @Override public void warning(DiagnosticWrapper wrapper) { if (external != null) { external.warning(wrapper); } } @Override public void error(DiagnosticWrapper wrapper) { if (external != null) { external.error(wrapper); } } }; private boolean shouldShowNotification = true; public void setShouldShowNotification(boolean val) { shouldShowNotification = val; } public void setLogger(ILogger logger) { this.external = logger; } public void setOnResultListener(ApkBuilder.OnResultListener listener) { onResultListener = listener; } @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Notification notification = setupNotification(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { startForeground(201, notification); } else { startForeground(201, notification, FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED); } return START_STICKY; } private Notification setupNotification() { return new NotificationCompat.Builder(this, createNotificationChannel()) .setContentTitle(getString(R.string.app_name)) .setSmallIcon(R.drawable.ic_stat_code) .setContentText("Preparing") .setPriority(NotificationCompat.PRIORITY_HIGH) .setOngoing(true) .setProgress(100, 0, true) .build(); } private void updateNotification(String title, String message, int progress) { updateNotification(title, message, progress, NotificationCompat.PRIORITY_LOW); } private void updateNotification(String title, String message, int progress, int priority) { new Handler(Looper.getMainLooper()) .post( () -> { NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "Compiler") .setContentTitle(title) .setContentText(message) .setSmallIcon(R.drawable.ic_stat_code) .setPriority(priority); if (progress != -1) { builder.setProgress(100, progress, false); } NotificationManagerCompat.from(this).notify(201, builder.build()); }); } private String createNotificationChannel() { NotificationChannelCompat channel = new NotificationChannelCompat.Builder("Compiler", NotificationManagerCompat.IMPORTANCE_HIGH) .setName("Compiler service") .setDescription("Foreground notification for the compiler") .build(); NotificationManagerCompat.from(this).createNotificationChannel(channel); return "Compiler"; } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } public void compile(Project project, BuildType type) { mProject = project; if (mProject == null) { if (onResultListener != null) { mMainHandler.post( () -> onResultListener.onComplete( false, "Failed to open " + "project (Have you opened a project?)")); } if (shouldShowNotification) { updateNotification( "Compilation failed", "Unable to open project", -1, NotificationCompat.PRIORITY_HIGH); } return; } project.setCompiling(true); ProgressIndicator indicator = new ProgressIndicator(); ProgressManager.getInstance() .runAsync( () -> { try { if (true) { buildProject(project, type); } else { buildMainModule(project, type); } } finally { project.setCompiling(false); } }, i -> {}, indicator); } private void buildProject(Project project, BuildType type) { boolean success = true; try { ProjectBuilder projectBuilder = new ProjectBuilder(project, logger); projectBuilder.setTaskListener(this::updateNotification); projectBuilder.build(type); } catch (Throwable e) { String message; if (BuildConfig.DEBUG) { message = Log.getStackTraceString(e); } else { message = e.getMessage(); } mMainHandler.post(() -> onResultListener.onComplete(false, message)); success = false; } report(success, type, project.getMainModule()); } private void buildMainModule(Project project, BuildType type) { Module module = project.getMainModule(); Builder<? extends Module> projectBuilder = getBuilderForProject(module, type); module.clear(); module.index(); boolean success = true; projectBuilder.setTaskListener(this::updateNotification); try { projectBuilder.build(type); } catch (Exception e) { String message; if (BuildConfig.DEBUG) { message = Log.getStackTraceString(e); } else { message = e.getMessage(); } mMainHandler.post(() -> onResultListener.onComplete(false, message)); success = false; } report(success, type, module); } private void report(boolean success, BuildType type, Module module) { if (success) { mMainHandler.post(() -> onResultListener.onComplete(true, "Success")); } String projectName = "Project"; if (!success) { updateNotification( projectName, getString(R.string.compilation_result_failed), -1, NotificationCompat.PRIORITY_HIGH); } else { if (shouldShowNotification) { mMainHandler.post( () -> { NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "Compiler") .setSmallIcon(R.drawable.ic_stat_code) .setContentTitle(projectName) .setContentText(getString(R.string.compilation_result_success)); if (type != BuildType.AAB) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType( ApkInstaller.uriFromFile( this, new File(module.getBuildDirectory(), "bin/signed.apk")), "application/vnd.android.package-archive"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); PendingIntent pending = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); builder.addAction( new NotificationCompat.Action( 0, getString(R.string.compilation_button_install), pending)); } NotificationManagerCompat.from(this).notify(201, builder.build()); }); } } stopSelf(); stopForeground(true); } private Builder<? extends Module> getBuilderForProject(Module module, BuildType type) { if (module instanceof AndroidModule) { if (type == BuildType.AAB) { return new AndroidAppBundleBuilder(mProject, (AndroidModule) module, logger); } return new AndroidAppBuilder(mProject, (AndroidModule) module, logger); } return null; } }
9,900
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
IndexServiceConnection.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/service/IndexServiceConnection.java
package com.tyron.code.service; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.IBinder; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.tyron.builder.log.ILogger; import com.tyron.builder.log.LogViewModel; import com.tyron.builder.model.ProjectSettings; import com.tyron.builder.project.Project; import com.tyron.code.ui.editor.impl.FileEditorManagerImpl; import com.tyron.code.ui.main.MainViewModel; import com.tyron.code.ui.project.ProjectManager; import com.tyron.fileeditor.api.FileEditor; import com.tyron.fileeditor.api.FileEditorSavedState; import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** Handles the communication between the Index service and the main fragment */ public class IndexServiceConnection implements ServiceConnection { private final MainViewModel mMainViewModel; private final LogViewModel mLogViewModel; private final ILogger mLogger; private Project mProject; public IndexServiceConnection(MainViewModel mainViewModel, LogViewModel logViewModel) { mMainViewModel = mainViewModel; mLogViewModel = logViewModel; mLogger = ILogger.wrap(logViewModel); } public void setProject(Project project) { mProject = project; } @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { IndexService.IndexBinder binder = (IndexService.IndexBinder) iBinder; try { mProject.setCompiling(true); binder.index(mProject, new TaskListener(), mLogger); } finally { mProject.setCompiling(false); } } @Override public void onServiceDisconnected(ComponentName componentName) { mMainViewModel.setIndexing(false); mMainViewModel.setCurrentState(null); } private class TaskListener implements ProjectManager.TaskListener { @Override public void onTaskStarted(String message) { mMainViewModel.setCurrentState(message); } @SuppressWarnings("ConstantConditions") @Override public void onComplete(Project project, boolean success, String message) { mMainViewModel.setIndexing(false); mMainViewModel.setCurrentState(null); if (success) { Project currentProject = ProjectManager.getInstance().getCurrentProject(); if (project.equals(currentProject)) { mMainViewModel.setToolbarTitle(project.getRootFile().getName()); } } else { if (mMainViewModel.getBottomSheetState().getValue() != BottomSheetBehavior.STATE_EXPANDED) { mMainViewModel.setBottomSheetState(BottomSheetBehavior.STATE_HALF_EXPANDED); } mLogViewModel.e(LogViewModel.BUILD_LOG, message); } } } public static List<FileEditor> getOpenedFiles(ProjectSettings settings) { String openedFilesString = settings.getString(ProjectSettings.SAVED_EDITOR_FILES, null); if (openedFilesString != null) { try { Type type = new TypeToken<List<FileEditorSavedState>>() {}.getType(); List<FileEditorSavedState> savedStates = new Gson().fromJson(openedFilesString, type); return savedStates.stream() .filter(it -> it.getFile().exists()) .map(FileEditorManagerImpl.getInstance()::openFile) .collect(Collectors.toList()); } catch (Throwable e) { // ignored, users may have edited the file manually and is corrupt // just return an empty editor list } } return new ArrayList<>(); } public static void restoreFileEditors(Project currentProject, MainViewModel viewModel) { List<FileEditor> openedFiles = getOpenedFiles(currentProject.getSettings()); List<FileEditor> value = viewModel.getFiles().getValue(); if (value != null) { List<File> toClose = value.stream() .map(FileEditor::getFile) .filter( file -> openedFiles.stream().noneMatch(editor -> file.equals(editor.getFile()))) .collect(Collectors.toList()); toClose.forEach(FileEditorManagerImpl.getInstance()::closeFile); } viewModel.setFiles(openedFiles); } }
4,276
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
IndexService.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/service/IndexService.java
package com.tyron.code.service; import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED; import android.app.Notification; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import androidx.core.app.NotificationChannelCompat; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.tyron.builder.log.ILogger; import com.tyron.builder.project.Project; import com.tyron.code.ui.project.ProjectManager; import java.lang.ref.WeakReference; import org.codeassist.unofficial.R; public class IndexService extends Service { private static final int NOTIFICATION_ID = 23; private final Handler mMainHandler = new Handler(Looper.getMainLooper()); private final IndexBinder mBinder = new IndexBinder(this); public IndexService() {} public static class IndexBinder extends Binder { public final WeakReference<IndexService> mIndexServiceReference; public IndexBinder(IndexService service) { mIndexServiceReference = new WeakReference<>(service); } public void index(Project project, ProjectManager.TaskListener listener, ILogger logger) { IndexService service = mIndexServiceReference.get(); if (service == null) { listener.onComplete(project, false, "Index service is null!"); } else { service.index(project, listener, logger); } } } public IBinder onBind(Intent intent) { return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Notification notification = new NotificationCompat.Builder(this, createNotificationChannel()) .setProgress(100, 0, true) .setSmallIcon(R.drawable.ic_stat_code) .setContentTitle("Indexing") .setContentText("Preparing") .build(); updateNotification(notification); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { startForeground(NOTIFICATION_ID, notification); } else { startForeground(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED); } return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); } private void index(Project project, ProjectManager.TaskListener listener, ILogger logger) { ProjectManager.TaskListener delegate = new ProjectManager.TaskListener() { @Override public void onTaskStarted(String message) { Notification notification = new NotificationCompat.Builder(IndexService.this, "Index") .setProgress(100, 0, true) .setSmallIcon(R.drawable.ic_stat_code) .setContentTitle("Indexing") .setContentText(message) .build(); updateNotification(notification); mMainHandler.post(() -> listener.onTaskStarted(message)); } @Override public void onComplete(Project project, boolean success, String message) { mMainHandler.post(() -> listener.onComplete(project, success, message)); stopForeground(true); stopSelf(); } }; try { ProjectManager.getInstance().openProject(project, true, delegate, logger); } catch (Throwable e) { stopForeground(true); Notification notification = new NotificationCompat.Builder(IndexService.this, "Index") .setProgress(100, 0, true) .setSmallIcon(R.drawable.ic_stat_code) .setContentTitle("Indexing error") .setContentText("Unknown error: " + e.getMessage()) .build(); updateNotification(notification); stopSelf(); throw e; } } private String createNotificationChannel() { NotificationChannelCompat channel = new NotificationChannelCompat.Builder("Index", NotificationManagerCompat.IMPORTANCE_NONE) .setName("Index Service") .setDescription("Service that downloads libraries in the foreground") .build(); NotificationManagerCompat.from(this).createNotificationChannel(channel); return "Index"; } private void updateNotification(Notification notification) { NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification); } }
4,493
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompilerServiceConnection.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/service/CompilerServiceConnection.java
package com.tyron.code.service; import android.content.ComponentName; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.IBinder; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.tyron.builder.compiler.BuildType; import com.tyron.builder.log.ILogger; import com.tyron.builder.log.LogViewModel; import com.tyron.builder.model.DiagnosticWrapper; import com.tyron.code.ApplicationLoader; import com.tyron.code.ui.main.MainViewModel; import com.tyron.code.ui.project.ProjectManager; import com.tyron.code.util.ApkInstaller; import com.tyron.common.SharedPreferenceKeys; import java.io.File; import java.util.Objects; import javax.tools.Diagnostic; public class CompilerServiceConnection implements ServiceConnection { private final MainViewModel mMainViewModel; private final LogViewModel mLogViewModel; private CompilerService mService; private BuildType mBuildType; private boolean mCompiling; public CompilerServiceConnection(MainViewModel mainViewModel, LogViewModel logViewModel) { mMainViewModel = mainViewModel; mLogViewModel = logViewModel; } public void setBuildType(BuildType type) { mBuildType = type; } public boolean isCompiling() { return mCompiling; } public void setShouldShowNotification(boolean val) { if (mService != null) { mService.setShouldShowNotification(val); } } @Override public void onServiceConnected(ComponentName name, IBinder binder) { mService = ((CompilerService.CompilerBinder) binder).getCompilerService(); if (mService == null) { mLogViewModel.e(LogViewModel.BUILD_LOG, "CompilerService is null!"); return; } mService.setLogger(ILogger.wrap(mLogViewModel)); mService.setShouldShowNotification(false); mService.setOnResultListener( (success, message) -> { mMainViewModel.setCurrentState(null); mMainViewModel.setIndexing(false); if (success) { mLogViewModel.d(LogViewModel.BUILD_LOG, message); mLogViewModel.clear(LogViewModel.APP_LOG); File file = new File( ProjectManager.getInstance() .getCurrentProject() .getMainModule() .getBuildDirectory(), "bin/signed.apk"); if (file.exists() && mBuildType != BuildType.AAB) { SharedPreferences preference = ApplicationLoader.getDefaultPreferences(); if (preference.getBoolean(SharedPreferenceKeys.INSTALL_APK_DIRECTLY, true)) { ApkInstaller.installApplication(mService, file.getAbsolutePath()); } else { mMainViewModel.setBottomSheetState(BottomSheetBehavior.STATE_HALF_EXPANDED); } DiagnosticWrapper wrapper = new DiagnosticWrapper(); wrapper.setKind(Diagnostic.Kind.NOTE); wrapper.setMessage("Generated APK has been saved to " + file.getAbsolutePath()); wrapper.setExtra("INSTALL"); wrapper.setSource(file); wrapper.setCode(""); wrapper.setOnClickListener( (view) -> { if (view == null || view.getContext() == null) { return; } ApkInstaller.installApplication(view.getContext(), file.getAbsolutePath()); }); mLogViewModel.d(LogViewModel.BUILD_LOG, wrapper); } } else { mLogViewModel.e(LogViewModel.BUILD_LOG, message); if (BottomSheetBehavior.STATE_COLLAPSED == Objects.requireNonNull(mMainViewModel.getBottomSheetState().getValue())) { mMainViewModel.setBottomSheetState(BottomSheetBehavior.STATE_HALF_EXPANDED); } } }); if (mBuildType != null) { mCompiling = true; mService.compile(ProjectManager.getInstance().getCurrentProject(), mBuildType); } } @Override public void onServiceDisconnected(ComponentName name) { mService = null; mMainViewModel.setCurrentState(null); mMainViewModel.setIndexing(false); mCompiling = false; } }
4,280
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CodeTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/CodeTemplate.java
package com.tyron.code.template; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; /** * Class for creating different templates for classes such as an interface, abstract or regular * classes */ public class CodeTemplate implements Parcelable { public static final Parcelable.Creator<CodeTemplate> CREATOR = new Parcelable.Creator<CodeTemplate>() { @Override public CodeTemplate createFromParcel(Parcel parcel) { return new CodeTemplate(parcel); } @Override public CodeTemplate[] newArray(int i) { return new CodeTemplate[i]; } }; /** Used to replace the template package name with the app's package name */ public static final String PACKAGE_NAME = "${packageName}"; public static final String CLASS_NAME = "${className}"; protected String mContents; public CodeTemplate() {} public CodeTemplate(Parcel in) { mContents = in.readString(); } public final String get() { setup(); return mContents; } public final void setContents(String contents) { mContents = contents; } /** Subclasses must call setContents(); */ public void setup() {} public String getName() { throw new IllegalStateException("getName() is not subclassed"); } public String getExtension() { throw new IllegalStateException("getExtension() is not subclassed"); } @NonNull @Override public String toString() { return getName(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mContents); } }
1,680
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaClassTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/java/JavaClassTemplate.java
package com.tyron.code.template.java; import android.os.Parcel; import com.tyron.code.template.CodeTemplate; public class JavaClassTemplate extends CodeTemplate { public JavaClassTemplate() {} public JavaClassTemplate(Parcel in) { super(in); } @Override public String getName() { return "Java class"; } @Override public void setup() { setContents( "package " + CodeTemplate.PACKAGE_NAME + ";\n" + "\npublic class " + CodeTemplate.CLASS_NAME + " {\n\t\n}"); } @Override public String getExtension() { return ".java"; } }
635
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AbstractTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/java/AbstractTemplate.java
package com.tyron.code.template.java; import android.os.Parcel; import com.tyron.code.template.CodeTemplate; public class AbstractTemplate extends JavaClassTemplate { public AbstractTemplate() {} public AbstractTemplate(Parcel in) { super(in); } @Override public String getName() { return "Abstract"; } @Override public void setup() { setContents( "package " + CodeTemplate.PACKAGE_NAME + ";\n" + "\npublic abstract" + " class " + CodeTemplate.CLASS_NAME + " {\n\t\n}"); } }
591
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
InterfaceTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/java/InterfaceTemplate.java
package com.tyron.code.template.java; import android.os.Parcel; import com.tyron.code.template.CodeTemplate; public class InterfaceTemplate extends JavaClassTemplate { public InterfaceTemplate() {} public InterfaceTemplate(Parcel in) { super(in); } @Override public String getName() { return "Interface"; } @Override public void setup() { setContents( "package " + CodeTemplate.PACKAGE_NAME + ";\n" + "\npublic interface " + CodeTemplate.CLASS_NAME + " {\n\t\n}"); } }
573
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
KotlinClassTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/kotlin/KotlinClassTemplate.java
package com.tyron.code.template.kotlin; import android.os.Parcel; import com.tyron.code.template.CodeTemplate; public class KotlinClassTemplate extends CodeTemplate { public KotlinClassTemplate() {} public KotlinClassTemplate(Parcel in) { super(in); } @Override public String getName() { return "Kotlin class"; } @Override public void setup() { setContents( "package " + CodeTemplate.PACKAGE_NAME + "\n\n" + "class " + CodeTemplate.CLASS_NAME + " {\n" + "\t" + "\n" + "}"); } @Override public String getExtension() { return ".kt"; } }
686
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
KotlinAbstractClassTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/kotlin/KotlinAbstractClassTemplate.java
package com.tyron.code.template.kotlin; import android.os.Parcel; import com.tyron.code.template.CodeTemplate; public class KotlinAbstractClassTemplate extends KotlinClassTemplate { public KotlinAbstractClassTemplate() {} public KotlinAbstractClassTemplate(Parcel in) { super(in); } @Override public String getName() { return "Kotlin Abstract Class"; } @Override public void setup() { setContents( "package " + CodeTemplate.PACKAGE_NAME + "\n\n" + "abstract class " + CodeTemplate.CLASS_NAME + " {\n" + "\t" + "\n" + "}"); } }
667
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
KotlinInterfaceTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/kotlin/KotlinInterfaceTemplate.java
package com.tyron.code.template.kotlin; import android.os.Parcel; import com.tyron.code.template.CodeTemplate; public class KotlinInterfaceTemplate extends KotlinClassTemplate { public KotlinInterfaceTemplate() {} public KotlinInterfaceTemplate(Parcel in) { super(in); } @Override public String getName() { return "Kotlin Interface"; } @Override public void setup() { setContents( "package " + CodeTemplate.PACKAGE_NAME + "\n\n" + "interface " + CodeTemplate.CLASS_NAME + " {\n" + "\t" + "\n" + "}"); } }
645
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LayoutTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/xml/LayoutTemplate.java
package com.tyron.code.template.xml; import android.os.Parcel; import com.tyron.code.template.CodeTemplate; public class LayoutTemplate extends CodeTemplate { public LayoutTemplate() {} public LayoutTemplate(Parcel in) { super(in); } @Override public String getName() { return "Layout XML"; } @Override public void setup() { setContents( "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" + " xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n" + " android:layout_width=\"match_parent\"\n" + " android:layout_height=\"match_parent\"\n" + " android:orientation=\"vertical\">\n" + "\n" + "</LinearLayout>"); } @Override public String getExtension() { return ".xml"; } }
839
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ActivityTemplate.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/template/android/ActivityTemplate.java
package com.tyron.code.template.android; import android.os.Parcel; import com.tyron.code.template.CodeTemplate; import com.tyron.code.template.java.JavaClassTemplate; public class ActivityTemplate extends JavaClassTemplate { public ActivityTemplate() { super(); } public ActivityTemplate(Parcel in) { super(in); } @Override public String getName() { return "Activity"; } @Override public void setup() { setContents( "package " + CodeTemplate.PACKAGE_NAME + ";\n\n" + "import android.app.Activity;\n" + "import android.os.Bundle;\n\n" + "public class " + CodeTemplate.CLASS_NAME + " extends Activity {\n\n" + " @Override\n" + " public void onCreate(Bundle savedInstanceState) {\n" + " super.onCreate(savedInstanceState);\n" + " }\n" + "}"); } }
950
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
PopupMenuHelper.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/util/PopupMenuHelper.java
package com.tyron.code.util; import androidx.appcompat.widget.ForwardingListener; import java.lang.reflect.Field; public class PopupMenuHelper { private PopupMenuHelper() {} private static final Field FORWARDING_FIELD; static { try { Class<?> aClass = Class.forName("androidx.appcompat.widget.ForwardingListener"); FORWARDING_FIELD = aClass.getDeclaredField("mForwarding"); FORWARDING_FIELD.setAccessible(true); } catch (Throwable e) { throw new Error(e); } } /** * Helper method to set the forwarding listener of a PopupMenu to be always forwarding touch * events * * @param forwardingListener must be an instance of ForwardingListener */ public static void setForwarding(ForwardingListener forwardingListener) { try { FORWARDING_FIELD.set(forwardingListener, true); } catch (IllegalAccessException e) { throw new Error(e); } } }
927
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
NoInsetFrameLayout.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/util/NoInsetFrameLayout.java
package com.tyron.code.util; import android.content.Context; import android.util.AttributeSet; import android.view.WindowInsets; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Used in situations where the layout is needed to resize in response to an input method while * still being able to draw behind status bars */ public class NoInsetFrameLayout extends FrameLayout { public NoInsetFrameLayout(@NonNull Context context) { super(context); } public NoInsetFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public NoInsetFrameLayout( @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public NoInsetFrameLayout( @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override public WindowInsets onApplyWindowInsets(WindowInsets insets) { return super.onApplyWindowInsets( insets.replaceSystemWindowInsets(0, 0, 0, insets.getSystemWindowInsetBottom())); } }
1,197
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CoordinatePopupMenu.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/util/CoordinatePopupMenu.java
package com.tyron.code.util; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.widget.PopupMenu; import java.lang.reflect.Field; import java.lang.reflect.Method; public class CoordinatePopupMenu extends PopupMenu { private static final Field sMenuPopupField; static { try { sMenuPopupField = PopupMenu.class.getDeclaredField("mPopup"); sMenuPopupField.setAccessible(true); } catch (Throwable e) { throw new Error(e); } } public CoordinatePopupMenu(@NonNull Context context, @NonNull View anchor) { super(context, anchor); } public CoordinatePopupMenu(@NonNull Context context, @NonNull View anchor, int gravity) { super(context, anchor, gravity); } public CoordinatePopupMenu( @NonNull Context context, @NonNull View anchor, int gravity, int popupStyleAttr, int popupStyleRes) { super(context, anchor, gravity, popupStyleAttr, popupStyleRes); } @Override public void show() { super.show(); } /** * Does nothing. This is to prevent unknown callers from dismissing the popup menu, use {@link * #dismissPopup()} instead */ @Override public void dismiss() { // do nothing } public void dismissPopup() { super.dismiss(); } public void show(int x, int y) { try { Object popup = sMenuPopupField.get(this); assert popup != null; Method show = popup.getClass().getDeclaredMethod("show", int.class, int.class); show.invoke(popup, x, y); } catch (Throwable e) { // should not happen, fallback to show() just in case show(); } } }
1,682
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CustomMutableLiveData.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/util/CustomMutableLiveData.java
package com.tyron.code.util; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import java.lang.reflect.Field; /** * A {@link LiveData} class which supports updating values but not notifying them. * * @param <T> The object this live data holds */ public class CustomMutableLiveData<T> extends MutableLiveData<T> { public CustomMutableLiveData() { super(); } public CustomMutableLiveData(T value) { super(value); } @Override public void setValue(T value) { super.setValue(value); } public void setValue(T value, boolean notify) { if (notify) { setValue(value); } else { setValueInternal(value); } } private void setValueInternal(T value) { try { Field mData = LiveData.class.getDeclaredField("mData"); mData.setAccessible(true); mData.set(this, value); } catch (Throwable e) { throw new RuntimeException(e); } } private void incrementVersion() { try { Field mVersion = LiveData.class.getDeclaredField("mVersion"); mVersion.setAccessible(true); Integer o = (Integer) mVersion.get(this); if (o == null) { o = 0; } mVersion.set(this, o + 1); } catch (Throwable e) { throw new RuntimeException(e); } } }
1,300
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ProjectUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/util/ProjectUtils.java
package com.tyron.code.util; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tyron.code.ui.file.tree.model.TreeFile; import com.tyron.ui.treeview.TreeNode; import java.io.File; public class ProjectUtils { /** * Utility method to get package name from a current directory, this traverses up the file * hierarchy until it reaches the "java" folder we can then workout the possible package name from * that * * @param directory the parent file of the class * @return null if name cannot be determined */ @Nullable public static String getPackageName(File directory) { if (!directory.isDirectory()) { return null; } File original = directory; while (!isJavaFolder(directory)) { if (directory == null) { return null; } directory = directory.getParentFile(); } String originalPath = original.getAbsolutePath(); String javaPath = directory.getAbsolutePath(); String cutPath = originalPath.replace(javaPath, ""); return formatPackageName(cutPath); } /** * Utility method to determine if the folder is the app/src/main/java folder * * @param file file to check * @return true if its the java folder */ private static boolean isJavaFolder(File file) { if (file == null) { return false; } if (!file.isDirectory()) { return false; } if (file.getName().equals("java")) { File parent = file.getParentFile(); if (parent == null) { return false; } else return parent.getName().equals("main"); } return false; } /** * Gets the parent directory of a node, if the node is already a directory then it is returned * * @param node the node to search * @return parent directory or itself if its already a directory */ public static File getDirectory(TreeNode<TreeFile> node) { File file = node.getContent().getFile(); if (file.isDirectory()) { return file; } else { return file.getParentFile(); } } /** * Formats a path into a package name eg. com/my/test into com.my.test * * @param path input path * @return formatted package name */ private static String formatPackageName(String path) { if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path.replace("/", "."); } public static boolean isResourceXMLDir(File dir) { if (dir == null) { return false; } File parent = dir.getParentFile(); if (parent != null) { return parent.getName().equals("res"); } return false; } public static boolean isResourceXMLFile(@NonNull File file) { if (!file.getName().endsWith(".xml")) { return false; } return isResourceXMLDir(file.getParentFile()); } public static boolean isLayoutXMLFile(@NonNull File file) { if (!file.getName().endsWith(".xml")) { return false; } if (file.getParentFile() != null) { File parent = file.getParentFile(); if (parent.isDirectory() && parent.getName().startsWith("layout")) { return isResourceXMLFile(file); } } return false; } }
3,266
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AllowChildInterceptDrawerLayout.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/util/AllowChildInterceptDrawerLayout.java
package com.tyron.code.util; import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.drawerlayout.widget.DrawerLayout; /** Allows horizontally scrolling child of drawer layouts to intercept the touch event. */ public class AllowChildInterceptDrawerLayout extends DrawerLayout { private final Rect rect = new Rect(); public AllowChildInterceptDrawerLayout(@NonNull Context context) { super(context); } public AllowChildInterceptDrawerLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public AllowChildInterceptDrawerLayout( @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { View scrollingChild = findScrollingChild(this, ev.getX(), ev.getY()); if (scrollingChild != null) { return false; } return super.onInterceptTouchEvent(ev); } /** * Recursively finds the view that can scroll horizontally to the end * * @param parent The starting parent to search * @param x The x point in the screen * @param y The y point in the screen * @return The scrolling view, null if no view is found */ private View findScrollingChild(ViewGroup parent, float x, float y) { int n = parent.getChildCount(); if (parent == this && n <= 1) { return null; } int start = 0; if (parent == this) { start = 1; } for (int i = start; i < n; i++) { View child = parent.getChildAt(i); if (child.getVisibility() != View.VISIBLE) { continue; } child.getHitRect(rect); if (rect.contains((int) x, (int) y)) { if (child.canScrollHorizontally(1)) { return child; } else if (child instanceof ViewGroup) { View v = findScrollingChild((ViewGroup) child, x - rect.left, y - rect.top); if (v != null) { return v; } } } } return null; } }
2,248
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ApkInstaller.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/util/ApkInstaller.java
package com.tyron.code.util; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.util.Log; import androidx.core.content.FileProvider; import java.io.File; import org.codeassist.unofficial.BuildConfig; public class ApkInstaller { private static final String TAG = ApkInstaller.class.getSimpleName(); public static void installApplication(Context context, String filePath) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType( uriFromFile(context, new File(filePath)), "application/vnd.android.package-archive"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { context.startActivity(intent); } catch (ActivityNotFoundException e) { e.printStackTrace(); Log.e(TAG, "Error in opening the file!"); } } public static Uri uriFromFile(Context context, File file) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file); } else { return Uri.fromFile(file); } } }
1,244
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/util/FileUtils.java
package com.tyron.code.util; import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.text.TextUtils; import android.util.Log; import com.tyron.code.ApplicationLoader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; public class FileUtils { private static Uri contentUri = null; @SuppressLint("NewApi") public static String getPath(final Uri uri) { // check here to KITKAT or new version final boolean isKitKat = true; String selection = null; String[] selectionArgs = null; // DocumentProvider if (isKitKat) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; String fullPath = getPathFromExtSD(split); if (fullPath != "") { return fullPath; } else { return null; } } // DownloadsProvider if (isDownloadsDocument(uri)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final String id; Cursor cursor = null; try { cursor = ApplicationLoader.applicationContext .getContentResolver() .query( uri, new String[] {MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null); if (cursor != null && cursor.moveToFirst()) { String fileName = cursor.getString(0); String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName; if (!TextUtils.isEmpty(path)) { return path; } } } finally { if (cursor != null) cursor.close(); } id = DocumentsContract.getDocumentId(uri); if (!TextUtils.isEmpty(id)) { if (id.startsWith("raw:")) { return id.replaceFirst("raw:", ""); } String[] contentUriPrefixesToTry = new String[] { "content://downloads/public_downloads", "content://downloads/my_downloads" }; for (String contentUriPrefix : contentUriPrefixesToTry) { try { final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id)); return getDataColumn(ApplicationLoader.applicationContext, contentUri, null, null); } catch (NumberFormatException e) { // In Android 8 and Android P the id is not a number return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", ""); } } } } else { final String id = DocumentsContract.getDocumentId(uri); if (id.startsWith("raw:")) { return id.replaceFirst("raw:", ""); } try { contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.parseLong(id)); } catch (NumberFormatException e) { e.printStackTrace(); } if (contentUri != null) { return getDataColumn(ApplicationLoader.applicationContext, contentUri, null, null); } } } // MediaProvider if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } selection = "_id=?"; selectionArgs = new String[] {split[1]}; return getDataColumn( ApplicationLoader.applicationContext, contentUri, selection, selectionArgs); } if (isGoogleDriveUri(uri)) { return getDriveFilePath(uri); } if (isWhatsAppFile(uri)) { return getFilePathForWhatsApp(uri); } if ("content".equalsIgnoreCase(uri.getScheme())) { if (isGooglePhotosUri(uri)) { return uri.getLastPathSegment(); } if (isGoogleDriveUri(uri)) { return getDriveFilePath(uri); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // return getFilePathFromURI(context,uri); return copyFileToInternalStorage(uri, "userfiles"); // return getRealPathFromURI(context,uri); } else { return getDataColumn(ApplicationLoader.applicationContext, uri, null, null); } } if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } } else { if (isWhatsAppFile(uri)) { return getFilePathForWhatsApp(uri); } if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = null; try { cursor = ApplicationLoader.applicationContext .getContentResolver() .query(uri, projection, selection, selectionArgs, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); if (cursor.moveToFirst()) { return cursor.getString(column_index); } } catch (Exception e) { e.printStackTrace(); } } } return null; } private static boolean fileExists(String filePath) { File file = new File(filePath); return file.exists(); } private static String getPathFromExtSD(String[] pathData) { final String type = pathData[0]; final String relativePath = "/" + pathData[1]; String fullPath = ""; // on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string // something like "71F8-2C0A", some kind of unique id per storage // don't know any API that can get the root path of that storage based on its id. // // so no "primary" type, but let the check here for other devices if ("primary".equalsIgnoreCase(type)) { fullPath = Environment.getExternalStorageDirectory() + relativePath; if (fileExists(fullPath)) { return fullPath; } } // Environment.isExternalStorageRemovable() is `true` for external and internal storage // so we cannot relay on it. // // instead, for each possible path, check if file exists // we'll start with secondary storage as this could be our (physically) removable sd card fullPath = System.getenv("SECONDARY_STORAGE") + relativePath; if (fileExists(fullPath)) { return fullPath; } fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath; if (fileExists(fullPath)) { return fullPath; } return fullPath; } private static String getDriveFilePath(Uri uri) { Uri returnUri = uri; Cursor returnCursor = ApplicationLoader.applicationContext .getContentResolver() .query(returnUri, null, null, null, null); /* * Get the column indexes of the data in the Cursor, * * move to the first row in the Cursor, get the data, * * and display it. * */ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); returnCursor.moveToFirst(); String name = (returnCursor.getString(nameIndex)); String size = (Long.toString(returnCursor.getLong(sizeIndex))); File file = new File(ApplicationLoader.applicationContext.getCacheDir(), name); try { InputStream inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri); FileOutputStream outputStream = new FileOutputStream(file); int read = 0; int maxBufferSize = 1024 * 1024; int bytesAvailable = inputStream.available(); // int bufferSize = 1024; int bufferSize = Math.min(bytesAvailable, maxBufferSize); final byte[] buffers = new byte[bufferSize]; while ((read = inputStream.read(buffers)) != -1) { outputStream.write(buffers, 0, read); } Log.e("File Size", "Size " + file.length()); inputStream.close(); outputStream.close(); Log.e("File Path", "Path " + file.getPath()); Log.e("File Size", "Size " + file.length()); } catch (Exception e) { Log.e("Exception", e.getMessage()); } return file.getPath(); } /*** * Used for Android Q+ * @param uri * @param newDirName if you want to create a directory, you can set this variable * @return */ private static String copyFileToInternalStorage(Uri uri, String newDirName) { Uri returnUri = uri; Cursor returnCursor = ApplicationLoader.applicationContext .getContentResolver() .query( returnUri, new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}, null, null, null); /* * Get the column indexes of the data in the Cursor, * * move to the first row in the Cursor, get the data, * * and display it. * */ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); returnCursor.moveToFirst(); String name = (returnCursor.getString(nameIndex)); String size = (Long.toString(returnCursor.getLong(sizeIndex))); File output; if (!newDirName.equals("")) { File dir = new File(ApplicationLoader.applicationContext.getFilesDir() + "/" + newDirName); if (!dir.exists()) { dir.mkdir(); } output = new File( ApplicationLoader.applicationContext.getFilesDir() + "/" + newDirName + "/" + name); } else { output = new File(ApplicationLoader.applicationContext.getFilesDir() + "/" + name); } try { InputStream inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri); FileOutputStream outputStream = new FileOutputStream(output); int read = 0; int bufferSize = 1024; final byte[] buffers = new byte[bufferSize]; while ((read = inputStream.read(buffers)) != -1) { outputStream.write(buffers, 0, read); } inputStream.close(); outputStream.close(); } catch (Exception e) { Log.e("Exception", e.getMessage()); } return output.getPath(); } private static String getFilePathForWhatsApp(Uri uri) { return copyFileToInternalStorage(uri, "whatsapp"); } private static String getDataColumn( Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = {column}; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; } private static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } private static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } private static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } private static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); } public static boolean isWhatsAppFile(Uri uri) { return "com.whatsapp.provider.media".equals(uri.getAuthority()); } private static boolean isGoogleDriveUri(Uri uri) { return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority()); } }
12,836
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AbstractCodeAnalyzer.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/AbstractCodeAnalyzer.java
package com.tyron.code.language; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tyron.builder.model.DiagnosticWrapper; import com.tyron.editor.Editor; import io.github.rosemoe.sora.lang.analysis.StyleReceiver; import io.github.rosemoe.sora.lang.styling.MappedSpans; import io.github.rosemoe.sora.lang.styling.Styles; import io.github.rosemoe.sora.text.CharPosition; import io.github.rosemoe.sora.text.ContentReference; import io.github.rosemoe.sora.widget.schemes.EditorColorScheme; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Token; import org.apache.commons.io.input.CharSequenceReader; public abstract class AbstractCodeAnalyzer<T> extends DiagnosticAnalyzeManager<T> { private final Map<Integer, Integer> mColorMap = new HashMap<>(); private StyleReceiver mReceiver; private Token mPreviousToken; private Styles mLastStyles; protected List<DiagnosticWrapper> mDiagnostics = new ArrayList<>(); public AbstractCodeAnalyzer() { setup(); } @Override public void setReceiver(@Nullable StyleReceiver receiver) { super.setReceiver(receiver); mReceiver = receiver; } @Override public void insert(CharPosition start, CharPosition end, CharSequence insertedContent) { rerunWithBg(); } @Override public void delete(CharPosition start, CharPosition end, CharSequence deletedContent) { rerunWithBg(); } @Override public void reset(@NonNull ContentReference content, @NonNull Bundle extraArguments) { super.reset(content, extraArguments); } @Override public void setDiagnostics(Editor editor, List<DiagnosticWrapper> diagnostics) { mDiagnostics = diagnostics; } public void setup() {} /** * Convenience method to map a color id to multiple token types * * @param id EditorColorScheme id * @param tokenTypes the Token types from the lexer */ protected void putColor(int id, int... tokenTypes) { for (int tokenType : tokenTypes) { putColor(id, tokenType); } } /** * Map a specific EditorColorScheme id to a token type * * @param id The color id from {@link EditorColorScheme} * @param tokenType the token type from the provided lexer */ protected void putColor(int id, int tokenType) { mColorMap.put(tokenType, id); } /** * @return The lexer that will be used to generate the tokens */ public abstract Lexer getLexer(CharStream input); public abstract void analyzeInBackground(CharSequence contents); public Integer getColor(int tokenType) { return mColorMap.get(tokenType); } /** * Called before {@link #analyze(StringBuilder, Delegate)} is called, commonly used to clear * object caches before starting the analysis */ protected void beforeAnalyze() {} @Override protected Styles analyze(StringBuilder text, Delegate<T> delegate) { Styles styles = new Styles(); boolean loaded = getExtraArguments().getBoolean("loaded", false); if (!loaded) { return styles; } beforeAnalyze(); MappedSpans.Builder result = new MappedSpans.Builder(1024); try { Lexer lexer = getLexer(CharStreams.fromReader(new CharSequenceReader(text))); while (!delegate.isCancelled()) { Token token = lexer.nextToken(); if (token == null) { break; } if (token.getType() == Token.EOF) { break; } boolean skip = onNextToken(token, styles, result); if (skip) { mPreviousToken = token; continue; } Integer id = getColor(token.getType()); if (id == null) { id = EditorColorScheme.TEXT_NORMAL; } result.addIfNeeded(token.getLine() - 1, token.getCharPositionInLine(), id); mPreviousToken = token; } if (mPreviousToken != null) { result.determine(mPreviousToken.getLine() - 1); } styles.spans = result.build(); styles.finishBuilding(); afterAnalyze(text, styles, result); if (mShouldAnalyzeInBg) { analyzeInBackground(text); } } catch (IOException e) { // ignored } mLastStyles = styles; return styles; } @Nullable protected Styles getLastStyles() { return mLastStyles; } /** Called after the analysis has been done, used to finalize the {@link MappedSpans.Builder} */ protected void afterAnalyze(CharSequence content, Styles styles, MappedSpans.Builder colors) {} @Nullable public Token getPreviousToken() { return mPreviousToken; } /** * Called when the lexer has moved to the next token * * @param currentToken the current token * @param styles * @param colors the current colors object, can be modified * @return true if the analyzer should skip on the next token */ public boolean onNextToken(Token currentToken, Styles styles, MappedSpans.Builder colors) { return false; } public void update(Styles styles) { mReceiver.setStyles(this, styles); } }
5,249
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BaseAnalyzeManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/BaseAnalyzeManager.java
package com.tyron.code.language; import android.os.Bundle; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.github.rosemoe.sora.lang.analysis.AnalyzeManager; import io.github.rosemoe.sora.lang.analysis.StyleReceiver; import io.github.rosemoe.sora.lang.styling.Styles; import io.github.rosemoe.sora.text.CharPosition; import io.github.rosemoe.sora.text.ContentReference; /** * Built-in implementation of {@link AnalyzeManager}. * * <p>This is a simple version without any incremental actions. * * <p>The analysis will always re-run when the text changes. Hopefully, it will stop previous * outdated runs by provide a {@link * io.github.rosemoe.sora.lang.analysis.SimpleAnalyzeManager.Delegate} object. * * @param <V> The shared object type that we get for auto-completion. */ public abstract class BaseAnalyzeManager<V> implements AnalyzeManager { private static final String LOG_TAG = "SimpleAnalyzeManager"; private static int sThreadId = 0; private StyleReceiver receiver; private ContentReference ref; private Bundle extraArguments; private volatile long newestRequestId; private final Object lock = new Object(); private V data; private AnalyzeThread thread; @Override public void setReceiver(@Nullable StyleReceiver receiver) { this.receiver = receiver; } @Override public void reset(@NonNull ContentReference content, @NonNull Bundle extraArguments) { this.ref = content; this.extraArguments = extraArguments; rerun(); } @Override public void insert(CharPosition start, CharPosition end, CharSequence insertedContent) { rerun(); } @Override public void delete(CharPosition start, CharPosition end, CharSequence deletedContent) { rerun(); } @Override public synchronized void rerun() { newestRequestId++; if (thread == null || !thread.isAlive()) { // Create new thread Log.v(LOG_TAG, "Starting a new thread for analysis"); thread = new AnalyzeThread(); thread.setDaemon(true); thread.setName("SplAnalyzer-" + nextThreadId()); thread.start(); } synchronized (lock) { lock.notify(); } } @Override public void destroy() { ref = null; extraArguments = null; newestRequestId = 0; data = null; if (thread != null && thread.isAlive()) { thread.cancel(); } thread = null; } private static synchronized int nextThreadId() { sThreadId++; return sThreadId; } /** * Get extra arguments set by {@link * io.github.rosemoe.sora.widget.CodeEditor#setText(CharSequence, Bundle)} */ public Bundle getExtraArguments() { return extraArguments; } /** Get data set by analyze thread */ @Nullable public V getData() { return data; } public AnalyzeThread getAnalyzeThread() { return thread; } /** * Analyze the given input. * * @param text A {@link StringBuilder} instance containing the text in editor. DO NOT SAVE THE * INSTANCE OR UPDATE IT. It is continuously used by this analyzer. * @param delegate A delegate used to check whether this invocation is outdated. You should stop * your logic if {@link Delegate#isCancelled()} returns true. * @return Styles created according to the text. */ protected abstract Styles analyze(StringBuilder text, Delegate<V> delegate); /** * Analyze thread. * * <p>The thread will keep alive unless there is any exception or {@link AnalyzeManager#destroy()} * is called. */ private class AnalyzeThread extends Thread { private volatile boolean cancelled = false; /** Single instance for text storing */ private final StringBuilder textContainer = new StringBuilder(); public void cancel() { cancelled = true; } @Override public void run() { Log.v(LOG_TAG, "Analyze thread started"); try { while (!cancelled) { final ContentReference text = ref; if (text != null) { long requestId = 0L; Styles result; V newData; // Do the analysis, until the requestId matches do { requestId = newestRequestId; Delegate<V> delegate = new Delegate<>(requestId); // Collect line contents textContainer.setLength(0); textContainer.ensureCapacity(text.length()); for (int i = 0; i < text.getLineCount() && requestId == newestRequestId; i++) { if (i != 0) { textContainer.append('\n'); } text.appendLineTo(textContainer, i); } // Invoke the implementation result = analyze(textContainer, delegate); newData = delegate.data; } while (requestId != newestRequestId); // Send result final StyleReceiver receiver = BaseAnalyzeManager.this.receiver; if (receiver != null) { receiver.setStyles(BaseAnalyzeManager.this, result); } data = newData; } // Wait for next time synchronized (lock) { lock.wait(); } } } catch (InterruptedException e) { Log.v(LOG_TAG, "Thread is interrupted."); } catch (Exception e) { Log.e(LOG_TAG, "Unexpected exception is thrown in the thread.", e); } } } /** Delegate between manager and analysis implementation */ public final class Delegate<T> { private final long myRequestId; private T data; public Delegate(long requestId) { myRequestId = requestId; } /** Set shared data */ public void setData(T value) { data = value; } /** Check whether the operation is cancelled */ public boolean isCancelled() { return myRequestId != newestRequestId; } } }
5,936
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
HighlightUtil.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/HighlightUtil.java
package com.tyron.code.language; import android.util.Log; import com.tyron.builder.model.DiagnosticWrapper; import com.tyron.completion.progress.ProgressManager; import com.tyron.editor.CharPosition; import com.tyron.editor.Editor; import io.github.rosemoe.sora.lang.styling.Span; import io.github.rosemoe.sora.lang.styling.Spans; import io.github.rosemoe.sora.lang.styling.Styles; import io.github.rosemoe.sora2.BuildConfig; import java.util.ArrayList; import java.util.List; import javax.tools.Diagnostic; public class HighlightUtil { public static void replaceSpan( Styles styles, Span newSpan, int startLine, int startColumn, int endLine, int endColumn) { for (int line = startLine; line <= endLine; line++) { ProgressManager.checkCanceled(); int start = (line == startLine ? startColumn : 0); int end = (line == endLine ? endColumn : Integer.MAX_VALUE); Spans.Reader read = styles.getSpans().read(); List<io.github.rosemoe.sora.lang.styling.Span> spans = new ArrayList<>(read.getSpansOnLine(line)); int increment; for (int i = 0; i < spans.size(); i += increment) { ProgressManager.checkCanceled(); io.github.rosemoe.sora.lang.styling.Span span = spans.get(i); increment = 1; if (span.column >= end) { break; } int spanEnd = (i + 1 >= spans.size() ? Integer.MAX_VALUE : spans.get(i + 1).column); if (spanEnd >= start) { int regionStartInSpan = Math.max(span.column, start); int regionEndInSpan = Math.min(end, spanEnd); if (regionStartInSpan == span.column) { if (regionEndInSpan != spanEnd) { increment = 2; io.github.rosemoe.sora.lang.styling.Span nSpan = span.copy(); nSpan.column = regionEndInSpan; spans.add(i + 1, nSpan); } span.problemFlags = newSpan.problemFlags; span.underlineColor = newSpan.underlineColor; span.style = newSpan.style; span.renderer = newSpan.renderer; } else { // regionStartInSpan > span.column if (regionEndInSpan == spanEnd - 1) { increment = 2; io.github.rosemoe.sora.lang.styling.Span nSpan = span.copy(); nSpan.column = regionStartInSpan; spans.add(i + 1, nSpan); span.problemFlags = newSpan.problemFlags; span.underlineColor = newSpan.underlineColor; span.style = newSpan.style; span.renderer = newSpan.renderer; } else { increment = 3; io.github.rosemoe.sora.lang.styling.Span span1 = span.copy(); span1.column = regionStartInSpan; span1.problemFlags = newSpan.problemFlags; span1.underlineColor = newSpan.underlineColor; span1.style = newSpan.style; span1.renderer = newSpan.renderer; io.github.rosemoe.sora.lang.styling.Span span2 = span.copy(); span2.column = regionEndInSpan; spans.add(i + 1, span1); spans.add(i + 2, span2); } } } } Spans.Modifier modify = styles.getSpans().modify(); modify.setSpansOnLine(line, spans); } } public static void markProblemRegion( Styles styles, int newFlag, int startLine, int startColumn, int endLine, int endColumn) { for (int line = startLine; line <= endLine; line++) { ProgressManager.checkCanceled(); int start = (line == startLine ? startColumn : 0); int end = (line == endLine ? endColumn : Integer.MAX_VALUE); Spans.Reader read = styles.getSpans().read(); List<io.github.rosemoe.sora.lang.styling.Span> spans = new ArrayList<>(read.getSpansOnLine(line)); int increment; for (int i = 0; i < spans.size(); i += increment) { ProgressManager.checkCanceled(); io.github.rosemoe.sora.lang.styling.Span span = spans.get(i); increment = 1; if (span.column >= end) { break; } int spanEnd = (i + 1 >= spans.size() ? Integer.MAX_VALUE : spans.get(i + 1).column); if (spanEnd >= start) { int regionStartInSpan = Math.max(span.column, start); int regionEndInSpan = Math.min(end, spanEnd); if (regionStartInSpan == span.column) { if (regionEndInSpan != spanEnd) { increment = 2; io.github.rosemoe.sora.lang.styling.Span nSpan = span.copy(); nSpan.column = regionEndInSpan; spans.add(i + 1, nSpan); } span.problemFlags |= newFlag; } else { // regionStartInSpan > span.column if (regionEndInSpan == spanEnd) { increment = 2; io.github.rosemoe.sora.lang.styling.Span nSpan = span.copy(); nSpan.column = regionStartInSpan; spans.add(i + 1, nSpan); nSpan.problemFlags |= newFlag; } else { increment = 3; io.github.rosemoe.sora.lang.styling.Span span1 = span.copy(); span1.column = regionStartInSpan; span1.problemFlags |= newFlag; io.github.rosemoe.sora.lang.styling.Span span2 = span.copy(); span2.column = regionEndInSpan; spans.add(i + 1, span1); spans.add(i + 2, span2); } } } } Spans.Modifier modify = styles.getSpans().modify(); modify.setSpansOnLine(line, spans); } } /** * Highlights the list of given diagnostics, taking care of conversion between 1-based offsets to * 0-based offsets. It also makes the Diagnostic eligible for shifting as the user types. */ public static void markDiagnostics( Editor editor, List<DiagnosticWrapper> diagnostics, Styles styles) { diagnostics.forEach( it -> { ProgressManager.checkCanceled(); try { int startLine; int startColumn; int endLine; int endColumn; if (it.getPosition() != DiagnosticWrapper.USE_LINE_POS) { if (it.getStartPosition() == -1) { it.setStartPosition(it.getPosition()); } if (it.getEndPosition() == -1) { it.setEndPosition(it.getPosition()); } CharPosition start = editor.getCharPosition((int) it.getStartPosition()); CharPosition end = editor.getCharPosition((int) it.getEndPosition()); int sLine = start.getLine(); int sColumn = start.getColumn(); int eLine = end.getLine(); int eColumn = end.getColumn(); // the editor does not support marking underline spans for the same start and end // index // to work around this, we just subtract one to the start index if (sLine == eLine && eColumn == sColumn) { sColumn--; eColumn++; } it.setStartLine(sLine); it.setEndLine(eLine); it.setStartColumn(sColumn); it.setEndColumn(eColumn); } startLine = it.getStartLine(); startColumn = it.getStartColumn(); endLine = it.getEndLine(); endColumn = it.getEndColumn(); int flag = it.getKind() == Diagnostic.Kind.ERROR ? Span.FLAG_ERROR : Span.FLAG_WARNING; markProblemRegion(styles, flag, startLine, startColumn, endLine, endColumn); } catch (IllegalArgumentException | IndexOutOfBoundsException e) { if (BuildConfig.DEBUG) { Log.d("HighlightUtil", "Failed to mark diagnostics", e); } } }); } /** Used in xml diagnostics where line is only given */ public static void setErrorSpan(Styles colors, int line) { try { Spans.Reader reader = colors.getSpans().read(); int realLine = line - 1; List<io.github.rosemoe.sora.lang.styling.Span> spans = reader.getSpansOnLine(realLine); for (io.github.rosemoe.sora.lang.styling.Span span : spans) { span.problemFlags = Span.FLAG_ERROR; } } catch (IndexOutOfBoundsException e) { // ignored } } public static void clearDiagnostics(Styles styles) { Spans spans = styles.getSpans(); Spans.Reader read = spans.read(); for (int i = 0; i < spans.getLineCount(); i++) { List<Span> spansOnLine = new ArrayList<>(read.getSpansOnLine(i)); for (Span span : spansOnLine) { span.problemFlags = 0; } spans.modify().setSpansOnLine(i, spansOnLine); } } }
8,805
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Language.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/Language.java
package com.tyron.code.language; import com.tyron.editor.Editor; import java.io.File; public interface Language { /** Subclasses return whether they support this file extension */ boolean isApplicable(File ext); /** * @param editor the editor instance * @return The specific language instance for this editor */ io.github.rosemoe.sora.lang.Language get(Editor editor); }
392
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DiagnosticAnalyzeManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/DiagnosticAnalyzeManager.java
package com.tyron.code.language; import android.os.Bundle; import androidx.annotation.NonNull; import com.tyron.builder.model.DiagnosticWrapper; import com.tyron.editor.Editor; import io.github.rosemoe.sora.lang.analysis.SimpleAnalyzeManager; import io.github.rosemoe.sora.text.ContentReference; import java.util.List; public abstract class DiagnosticAnalyzeManager<T> extends SimpleAnalyzeManager<T> { protected boolean mShouldAnalyzeInBg = false; public abstract void setDiagnostics(Editor editor, List<DiagnosticWrapper> diagnostics); public void rerunWithoutBg() { mShouldAnalyzeInBg = false; super.rerun(); } public void rerunWithBg() { mShouldAnalyzeInBg = true; super.rerun(); } @Override public void rerun() { mShouldAnalyzeInBg = false; super.rerun(); } @Override public void reset(@NonNull ContentReference content, @NonNull Bundle extraArguments) { if (extraArguments == null) { extraArguments = new Bundle(); } mShouldAnalyzeInBg = extraArguments.getBoolean("bg", false); super.reset(content, extraArguments); } @Override public Bundle getExtraArguments() { Bundle extraArguments = super.getExtraArguments(); if (extraArguments == null) { extraArguments = new Bundle(); } return extraArguments; } }
1,318
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LanguageManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/LanguageManager.java
package com.tyron.code.language; import com.tyron.code.language.groovy.Groovy; import com.tyron.code.language.java.Java; import com.tyron.code.language.json.Json; import com.tyron.code.language.kotlin.Kotlin; import com.tyron.code.language.xml.Xml; import com.tyron.editor.Editor; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class LanguageManager { private static LanguageManager Instance = null; public static LanguageManager getInstance() { if (Instance == null) { Instance = new LanguageManager(); } return Instance; } private final Set<Language> mLanguages = new HashSet<>(); private LanguageManager() { initLanguages(); } private void initLanguages() { mLanguages.addAll(Arrays.asList(new Xml(), new Java(), new Kotlin(), new Groovy(), new Json())); } public boolean supports(File file) { for (Language language : mLanguages) { if (language.isApplicable(file)) { return true; } } return false; } public io.github.rosemoe.sora.lang.Language get(Editor editor, File file) { for (Language lang : mLanguages) { if (lang.isApplicable(file)) { return lang.get(editor); } } return null; } }
1,269
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DiagnosticSpanMapUpdater.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/DiagnosticSpanMapUpdater.java
package com.tyron.code.language; import com.tyron.builder.model.DiagnosticWrapper; import io.github.rosemoe.sora.text.CharPosition; import io.github.rosemoe.sora.text.ContentReference; import java.util.List; public class DiagnosticSpanMapUpdater { public static void shiftDiagnosticsOnSingleLineInsert( List<DiagnosticWrapper> diagnostics, ContentReference ref, CharPosition start, CharPosition end) { int length = end.index - start.index; for (DiagnosticWrapper diagnostic : diagnostics) { if (!isValid(diagnostic)) { continue; } // diagnostic is located before the insertion index, its not included if (diagnostic.getEndPosition() <= end.index) { continue; } diagnostic.setStartPosition(diagnostic.getStartPosition() + length); diagnostic.setEndPosition(diagnostic.getEndPosition() + length); } } public static void shiftDiagnosticsOnSingleLineDelete( List<DiagnosticWrapper> diagnostics, ContentReference ref, CharPosition start, CharPosition end) { int length = end.index - start.index; for (DiagnosticWrapper diagnostic : diagnostics) { if (!isValid(diagnostic)) { continue; } if (diagnostic.getStartPosition() > start.index) { diagnostic.setStartPosition(diagnostic.getStartPosition() - length); } if (diagnostic.getEndPosition() > end.index) { diagnostic.setEndPosition(diagnostic.getEndPosition() - length); } } } public static void shiftDiagnosticsOnMultiLineDelete( List<DiagnosticWrapper> diagnostics, ContentReference ref, CharPosition start, CharPosition end) { int length = end.index - start.index; for (DiagnosticWrapper diagnostic : diagnostics) { if (!isValid(diagnostic)) { continue; } if (diagnostic.getStartPosition() < end.index) { continue; } diagnostic.setStartPosition(diagnostic.getStartPosition() - length); diagnostic.setEndPosition(diagnostic.getEndPosition() - length); } } public static void shiftDiagnosticsOnMultiLineInsert( List<DiagnosticWrapper> diagnostics, ContentReference ref, CharPosition start, CharPosition end) { int length = end.index - start.index; for (DiagnosticWrapper diagnostic : diagnostics) { if (!isValid(diagnostic)) { continue; } if (diagnostic.getEndPosition() < end.index) { continue; } diagnostic.setStartPosition(diagnostic.getStartPosition() + length); diagnostic.setEndPosition(diagnostic.getEndPosition() + length); } } public static boolean isValid(DiagnosticWrapper d) { return d.getStartPosition() >= 0 && d.getEndPosition() >= 0; } }
2,797
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
EditorFormatter.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/EditorFormatter.java
package com.tyron.code.language; import androidx.annotation.NonNull; /** Marker interface for languages that support formatting */ public interface EditorFormatter { /** * Formats the given CharSequence on the specified start and end indices. * * @param text The text to format. * @param startIndex The 0-based index of where the format starts * @param endIndex The 0-based index of where the format ends * @return The formatted text */ @NonNull CharSequence format(@NonNull CharSequence text, int startIndex, int endIndex); }
557
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AbstractAutoCompleteProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/AbstractAutoCompleteProvider.java
package com.tyron.code.language; import com.tyron.completion.model.CompletionList; import io.github.rosemoe.sora.lang.completion.CompletionItem; import java.util.List; import java.util.stream.Collectors; /** An auto complete provider that supports cancellation as the user types */ public abstract class AbstractAutoCompleteProvider { public final List<CompletionItem> getAutoCompleteItems(String prefix, int line, int column) { CompletionList list = getCompletionList(prefix, line, column); if (list == null) { return null; } return list.items.stream().map(CompletionItemWrapper::new).collect(Collectors.toList()); } public abstract CompletionList getCompletionList(String prefix, int line, int column); }
740
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompletionItemWrapper.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/CompletionItemWrapper.java
package com.tyron.code.language; import com.tyron.completion.java.drawable.CircleDrawable; import com.tyron.editor.Editor; import io.github.rosemoe.sora.lang.completion.CompletionItem; import io.github.rosemoe.sora.text.Content; import io.github.rosemoe.sora.widget.CodeEditor; /** A wrapper for {@link com.tyron.completion.model.CompletionItem} */ public class CompletionItemWrapper extends CompletionItem { private final com.tyron.completion.model.CompletionItem item; public CompletionItemWrapper(com.tyron.completion.model.CompletionItem item) { super(item.label, item.detail, new CircleDrawable(item.iconKind)); this.item = item; } @Override public void performCompletion(CodeEditor editor, Content text, int line, int column) { if (!(editor instanceof Editor)) { throw new IllegalArgumentException( "Cannot use CompletionItemWrapper on an editor that does not implement com.tyron.editor.Editor"); } Editor rawEditor = ((Editor) editor); item.handleInsert(rawEditor); } }
1,035
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaAnalyzer.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/java/JavaAnalyzer.java
package com.tyron.code.language.java; import android.content.SharedPreferences; import android.content.res.AssetManager; import android.os.Looper; import android.util.Log; import com.sun.source.tree.BlockTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import com.sun.tools.javac.api.ClientCodeWrapper; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.JCDiagnostic; import com.tyron.builder.model.DiagnosticWrapper; import com.tyron.builder.model.SourceFileObject; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.JavaModule; import com.tyron.builder.project.api.Module; import com.tyron.code.ApplicationLoader; import com.tyron.code.analyzer.SemanticAnalyzeManager; import com.tyron.code.analyzer.semantic.SemanticToken; import com.tyron.code.ui.editor.impl.text.rosemoe.CodeEditorView; import com.tyron.code.ui.project.ProjectManager; import com.tyron.common.SharedPreferenceKeys; import com.tyron.common.util.Debouncer; import com.tyron.completion.index.CompilerService; import com.tyron.completion.java.JavaCompilerProvider; import com.tyron.completion.java.compiler.CompileTask; import com.tyron.completion.java.compiler.CompilerContainer; import com.tyron.completion.java.compiler.JavaCompilerService; import com.tyron.completion.java.util.ErrorCodes; import com.tyron.completion.java.util.TreeUtil; import com.tyron.completion.progress.ProcessCanceledException; import com.tyron.completion.progress.ProgressManager; import com.tyron.editor.Editor; import io.github.rosemoe.sora.langs.textmate.theme.TextMateColorScheme; import io.github.rosemoe.sora.textmate.core.theme.IRawTheme; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.ref.WeakReference; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.stream.Collectors; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import kotlin.Unit; import kotlin.jvm.functions.Function0; import org.codeassist.unofficial.BuildConfig; public class JavaAnalyzer extends SemanticAnalyzeManager { private static final String GRAMMAR_NAME = "java.tmLanguage.json"; private static final String LANGUAGE_PATH = "textmate/java/syntaxes/java.tmLanguage.json"; private static final String CONFIG_PATH = "textmate/java/language-configuration.json"; public static JavaAnalyzer create(Editor editor) { try { AssetManager assetManager = ApplicationLoader.applicationContext.getAssets(); try (InputStreamReader config = new InputStreamReader(assetManager.open(CONFIG_PATH))) { return new JavaAnalyzer( editor, GRAMMAR_NAME, assetManager.open(LANGUAGE_PATH), config, ((TextMateColorScheme) ((CodeEditorView) editor).getColorScheme()).getRawTheme()); } } catch (Exception e) { throw new RuntimeException(e); } } private static final Debouncer sDebouncer = new Debouncer( Duration.ofMillis(700), Executors.newScheduledThreadPool( 1, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { ThreadGroup threadGroup = Looper.getMainLooper().getThread().getThreadGroup(); return new Thread(threadGroup, runnable, TAG); } })); private static final String TAG = JavaAnalyzer.class.getSimpleName(); private final WeakReference<Editor> mEditorReference; private final SharedPreferences mPreferences; public JavaAnalyzer( Editor editor, String grammarName, InputStream grammarIns, Reader languageConfiguration, IRawTheme theme) throws Exception { super(editor, grammarName, grammarIns, languageConfiguration, theme); mEditorReference = new WeakReference<>(editor); mPreferences = ApplicationLoader.getDefaultPreferences(); } @Override public List<SemanticToken> analyzeSpansAsync(CharSequence contents) { Editor editor = mEditorReference.get(); JavaCompilerService compiler = getCompiler(editor); if (compiler == null) { return null; } File currentFile = editor.getCurrentFile(); SourceFileObject object = new SourceFileObject(currentFile.toPath(), contents.toString(), Instant.now()); CompilerContainer container = compiler.compile(Collections.singletonList(object)); return container.get( task -> { JavaSemanticHighlighter highlighter = new JavaSemanticHighlighter(task.task); CompilationUnitTree root = task.root(currentFile); highlighter.scan(root, true); return highlighter.getTokens(); }); } @Override public void analyzeInBackground(CharSequence contents) { sDebouncer.cancel(); sDebouncer.schedule( cancel -> { doAnalyzeInBackground(cancel, contents); return Unit.INSTANCE; }); } private JavaCompilerService getCompiler(Editor editor) { Project project = ProjectManager.getInstance().getCurrentProject(); if (project == null) { return null; } if (project.isCompiling() || project.isIndexing()) { return null; } Module module = project.getModule(editor.getCurrentFile()); if (module instanceof JavaModule) { JavaCompilerProvider provider = CompilerService.getInstance().getIndex(JavaCompilerProvider.KEY); if (provider != null) { return provider.getCompiler(project, (JavaModule) module); } } return null; } private void doAnalyzeInBackground(Function0<Boolean> cancel, CharSequence contents) { Log.d(TAG, "doAnalyzeInBackground: called"); Editor editor = mEditorReference.get(); if (editor == null) { return; } if (cancel.invoke()) { return; } // do not compile the file if it not yet closed as it will cause issues when // compiling multiple files at the same time if (mPreferences.getBoolean(SharedPreferenceKeys.JAVA_ERROR_HIGHLIGHTING, true)) { JavaCompilerService service = getCompiler(editor); if (service != null) { File currentFile = editor.getCurrentFile(); if (currentFile == null) { return; } Module module = ProjectManager.getInstance().getCurrentProject().getModule(currentFile); if (!module.getFileManager().isOpened(currentFile)) { return; } try { if (service.getCachedContainer().isWriting()) { return; } ProgressManager.getInstance().runLater(() -> editor.setAnalyzing(true)); SourceFileObject sourceFileObject = new SourceFileObject(currentFile.toPath(), contents.toString(), Instant.now()); CompilerContainer container = service.compile(Collections.singletonList(sourceFileObject)); container.run( task -> { if (!cancel.invoke()) { List<DiagnosticWrapper> collect = task.diagnostics.stream() .map(d -> modifyDiagnostic(task, d)) .peek(it -> ProgressManager.checkCanceled()) .filter(d -> currentFile.equals(d.getSource())) .collect(Collectors.toList()); editor.setDiagnostics(collect); ProgressManager.getInstance().runLater(() -> editor.setAnalyzing(false), 300); } }); } catch (Throwable e) { if (e instanceof ProcessCanceledException) { throw e; } if (BuildConfig.DEBUG) { Log.e(TAG, "Unable to get diagnostics", e); } service.destroy(); ProgressManager.getInstance().runLater(() -> editor.setAnalyzing(false)); } } } } private DiagnosticWrapper modifyDiagnostic( CompileTask task, Diagnostic<? extends JavaFileObject> diagnostic) { DiagnosticWrapper wrapped = new DiagnosticWrapper(diagnostic); if (diagnostic instanceof ClientCodeWrapper.DiagnosticSourceUnwrapper) { Trees trees = Trees.instance(task.task); SourcePositions positions = trees.getSourcePositions(); JCDiagnostic jcDiagnostic = ((ClientCodeWrapper.DiagnosticSourceUnwrapper) diagnostic).d; JCDiagnostic.DiagnosticPosition diagnosticPosition = jcDiagnostic.getDiagnosticPosition(); JCTree tree = diagnosticPosition.getTree(); if (tree != null) { TreePath treePath = trees.getPath(task.root(), tree); if (treePath == null) { return wrapped; } String code = jcDiagnostic.getCode(); long start = diagnostic.getStartPosition(); long end = diagnostic.getEndPosition(); switch (code) { case ErrorCodes.MISSING_RETURN_STATEMENT: TreePath block = TreeUtil.findParentOfType(treePath, BlockTree.class); if (block != null) { // show error span only at the end parenthesis end = positions.getEndPosition(task.root(), block.getLeaf()) + 1; start = end - 2; } break; case ErrorCodes.DEPRECATED: if (treePath.getLeaf().getKind() == Tree.Kind.METHOD) { MethodTree methodTree = (MethodTree) treePath.getLeaf(); if (methodTree.getBody() != null) { start = positions.getStartPosition(task.root(), methodTree); end = positions.getStartPosition(task.root(), methodTree.getBody()); } } break; } wrapped.setStartPosition(start); wrapped.setEndPosition(end); } } return wrapped; } }
10,146
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaLanguage.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/java/JavaLanguage.java
package com.tyron.code.language.java; import android.os.Bundle; import android.util.Log; import androidx.annotation.NonNull; import com.tyron.code.analyzer.BaseTextmateAnalyzer; import com.tyron.code.language.CompletionItemWrapper; import com.tyron.code.language.EditorFormatter; import com.tyron.completion.model.CompletionItem; import com.tyron.completion.model.CompletionList; import com.tyron.editor.Editor; import io.github.rosemoe.editor.langs.java.JavaTextTokenizer; import io.github.rosemoe.editor.langs.java.Tokens; import io.github.rosemoe.sora.lang.Language; import io.github.rosemoe.sora.lang.analysis.AnalyzeManager; import io.github.rosemoe.sora.lang.completion.CompletionCancelledException; import io.github.rosemoe.sora.lang.completion.CompletionHelper; import io.github.rosemoe.sora.lang.completion.CompletionPublisher; import io.github.rosemoe.sora.lang.smartEnter.NewlineHandleResult; import io.github.rosemoe.sora.lang.smartEnter.NewlineHandler; import io.github.rosemoe.sora.text.CharPosition; import io.github.rosemoe.sora.text.ContentReference; import io.github.rosemoe.sora.text.TextUtils; import io.github.rosemoe.sora.util.MyCharacter; import io.github.rosemoe.sora.widget.SymbolPairMatch; import java.io.ByteArrayInputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; public class JavaLanguage implements Language, EditorFormatter { private final Editor mEditor; private final BaseTextmateAnalyzer mAnalyzer; public JavaLanguage(Editor editor) { mEditor = editor; mAnalyzer = JavaAnalyzer.create(editor); } public boolean isAutoCompleteChar(char p1) { return p1 == '.' || MyCharacter.isJavaIdentifierPart(p1); } public int getIndentAdvance(String p1) { JavaTextTokenizer tokenizer = new JavaTextTokenizer(p1); Tokens token; int advance = 0; while ((token = tokenizer.directNextToken()) != Tokens.EOF) { switch (token) { case LBRACE: advance++; break; } } return (advance * getTabWidth()); } public int getFormatIndent(String line) { JavaTextTokenizer tokenizer = new JavaTextTokenizer(line); Tokens token; int advance = 0; while ((token = tokenizer.directNextToken()) != Tokens.EOF) { switch (token) { case LBRACE: advance++; break; case RBRACE: advance--; } } return (advance * getTabWidth()); } @NonNull @Override public AnalyzeManager getAnalyzeManager() { return mAnalyzer; } @Override public int getInterruptionLevel() { return INTERRUPTION_LEVEL_SLIGHT; } @Override public void requireAutoComplete( @NonNull ContentReference content, @NonNull CharPosition position, @NonNull CompletionPublisher publisher, @NonNull Bundle extraArguments) throws CompletionCancelledException { char c = content.charAt(position.getIndex() - 1); if (!isAutoCompleteChar(c)) { return; } String prefix = CompletionHelper.computePrefix(content, position, this::isAutoCompleteChar); JavaAutoCompleteProvider provider = new JavaAutoCompleteProvider(mEditor); CompletionList list = provider.getCompletionList(prefix, position.getLine(), position.getColumn()); if (list == null) { return; } for (CompletionItem item : list.getItems()) { CompletionItemWrapper wrapper = new CompletionItemWrapper(item); publisher.addItem(wrapper); } } @Override public int getIndentAdvance(@NonNull ContentReference content, int line, int column) { String text = content.getLine(line).substring(0, column); return getIndentAdvance(text); } @Override public boolean useTab() { return true; } public int getTabWidth() { return 4; } @Override public CharSequence format(CharSequence p1) { return format(p1, 0, p1.length()); } @NonNull @Override public CharSequence format(@NonNull CharSequence text, int start, int end) { CharSequence formatted = null; try { StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); com.google.googlejavaformat.java.Main main = new com.google.googlejavaformat.java.Main( new PrintWriter(out, true), new PrintWriter(err, true), new ByteArrayInputStream(text.toString().getBytes(StandardCharsets.UTF_8))); int exitCode = main.format("-"); formatted = out.toString(); if (exitCode != 0) { formatted = text; } } catch (Exception e) { } if (formatted == null) { formatted = text; } return formatted; } @Override public SymbolPairMatch getSymbolPairs() { return new SymbolPairMatch.DefaultSymbolPairs(); } private final NewlineHandler[] newLineHandlers = new NewlineHandler[] { new BraceHandler(), new TwoIndentHandler(), new JavaDocStartHandler(), new JavaDocHandler() }; @Override public NewlineHandler[] getNewlineHandlers() { return newLineHandlers; } @Override public void destroy() {} class TwoIndentHandler implements NewlineHandler { @Override public boolean matchesRequirement(String beforeText, String afterText) { Log.d("BeforeText", beforeText); if (beforeText.replace("\r", "").trim().startsWith(".")) { return false; } return beforeText.endsWith(")") && !afterText.startsWith(";"); } @Override public NewlineHandleResult handleNewline(String beforeText, String afterText, int tabSize) { int count = TextUtils.countLeadingSpaceCount(beforeText, tabSize); int advanceAfter = getIndentAdvance(afterText) + (4 * 2); String text; StringBuilder sb = new StringBuilder() .append('\n') .append(text = TextUtils.createIndent(count + advanceAfter, tabSize, useTab())); int shiftLeft = 0; return new NewlineHandleResult(sb, shiftLeft); } } class BraceHandler implements NewlineHandler { @Override public boolean matchesRequirement(String beforeText, String afterText) { return beforeText.endsWith("{") && afterText.startsWith("}"); } @Override public NewlineHandleResult handleNewline(String beforeText, String afterText, int tabSize) { int count = TextUtils.countLeadingSpaceCount(beforeText, tabSize); int advanceBefore = getIndentAdvance(beforeText); int advanceAfter = getIndentAdvance(afterText); String text; StringBuilder sb = new StringBuilder("\n") .append(TextUtils.createIndent(count + advanceBefore, tabSize, useTab())) .append('\n') .append(text = TextUtils.createIndent(count + advanceAfter, tabSize, useTab())); int shiftLeft = text.length() + 1; return new NewlineHandleResult(sb, shiftLeft); } } class JavaDocStartHandler implements NewlineHandler { private boolean shouldCreateEnd = true; @Override public boolean matchesRequirement(String beforeText, String afterText) { return beforeText.trim().startsWith("/**"); } @Override public NewlineHandleResult handleNewline(String beforeText, String afterText, int tabSize) { int count = TextUtils.countLeadingSpaceCount(beforeText, tabSize); int advanceAfter = getIndentAdvance(afterText); String text = ""; StringBuilder sb = new StringBuilder() .append("\n") .append(TextUtils.createIndent(count + advanceAfter, tabSize, useTab())) .append(" * "); if (shouldCreateEnd) { sb.append("\n") .append(text = TextUtils.createIndent(count + advanceAfter, tabSize, useTab())) .append(" */"); } return new NewlineHandleResult(sb, text.length() + 4); } } class JavaDocHandler implements NewlineHandler { @Override public boolean matchesRequirement(String beforeText, String afterText) { return beforeText.trim().startsWith("*") && !beforeText.trim().startsWith("*/"); } @Override public NewlineHandleResult handleNewline(String beforeText, String afterText, int tabSize) { int count = TextUtils.countLeadingSpaceCount(beforeText, tabSize); int advanceAfter = getIndentAdvance(afterText); StringBuilder sb = new StringBuilder() .append("\n") .append(TextUtils.createIndent(count + advanceAfter, tabSize, useTab())) .append("* "); return new NewlineHandleResult(sb, 0); } } }
8,639
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Java.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/java/Java.java
package com.tyron.code.language.java; import com.tyron.code.language.Language; import com.tyron.editor.Editor; import java.io.File; public class Java implements Language { @Override public boolean isApplicable(File ext) { return ext.getName().endsWith(".java"); } @Override public io.github.rosemoe.sora.lang.Language get(Editor editor) { return new JavaLanguage(editor); } }
400
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
IncrementalJavaAnalyzeManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/java/IncrementalJavaAnalyzeManager.java
package com.tyron.code.language.java; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.github.rosemoe.sora.lang.analysis.IncrementalAnalyzeManager; import io.github.rosemoe.sora.lang.analysis.StyleReceiver; import io.github.rosemoe.sora.lang.styling.Span; import io.github.rosemoe.sora.text.CharPosition; import io.github.rosemoe.sora.text.ContentReference; import java.util.List; import org.jetbrains.kotlin.com.intellij.lang.java.lexer.JavaLexer; import org.jetbrains.kotlin.com.intellij.lexer.Lexer; import org.jetbrains.kotlin.com.intellij.lexer.LexerPosition; import org.jetbrains.kotlin.com.intellij.pom.java.LanguageLevel; public class IncrementalJavaAnalyzeManager implements IncrementalAnalyzeManager<LexerPosition, Object> { private final Lexer mLexer; public IncrementalJavaAnalyzeManager() { mLexer = new JavaLexer(LanguageLevel.HIGHEST); } @Override public LexerPosition getInitialState() { return mLexer.getCurrentPosition(); } @Override public LineTokenizeResult<LexerPosition, Object> getState(int line) { return null; } @Override public boolean stateEquals(LexerPosition state, LexerPosition another) { return state.equals(another); } @Override public LineTokenizeResult<LexerPosition, Object> tokenizeLine( CharSequence line, LexerPosition state) { return null; } @Override public List<Span> generateSpansForLine(LineTokenizeResult<LexerPosition, Object> tokens) { return null; } @Override public void setReceiver(@Nullable StyleReceiver receiver) {} @Override public void reset(@NonNull ContentReference content, @NonNull Bundle extraArguments) { mLexer.start(content.getReference().toString()); } @Override public void insert(CharPosition start, CharPosition end, CharSequence insertedContent) {} @Override public void delete(CharPosition start, CharPosition end, CharSequence deletedContent) {} @Override public void rerun() {} @Override public void destroy() {} }
2,061
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaAutoCompleteProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/java/JavaAutoCompleteProvider.java
package com.tyron.code.language.java; import android.content.SharedPreferences; import androidx.annotation.Nullable; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.JavaModule; import com.tyron.builder.project.api.Module; import com.tyron.code.ApplicationLoader; import com.tyron.code.language.AbstractAutoCompleteProvider; import com.tyron.code.ui.project.ProjectManager; import com.tyron.common.SharedPreferenceKeys; import com.tyron.completion.main.CompletionEngine; import com.tyron.completion.model.CompletionList; import com.tyron.editor.Editor; import java.util.Optional; public class JavaAutoCompleteProvider extends AbstractAutoCompleteProvider { private final Editor mEditor; private final SharedPreferences mPreferences; public JavaAutoCompleteProvider(Editor editor) { mEditor = editor; mPreferences = ApplicationLoader.getDefaultPreferences(); } @Nullable @Override public CompletionList getCompletionList(String prefix, int line, int column) { if (!mPreferences.getBoolean(SharedPreferenceKeys.JAVA_CODE_COMPLETION, true)) { return null; } Project project = ProjectManager.getInstance().getCurrentProject(); if (project == null) { return null; } Module currentModule = project.getModule(mEditor.getCurrentFile()); if (currentModule instanceof JavaModule) { Optional<CharSequence> content = currentModule.getFileManager().getFileContent(mEditor.getCurrentFile()); if (content.isPresent()) { return CompletionEngine.getInstance() .complete( project, currentModule, mEditor, mEditor.getCurrentFile(), content.get().toString(), prefix, line, column, mEditor.getCaret().getStart()); } } return null; } }
1,917
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaSemanticHighlighter.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/java/JavaSemanticHighlighter.java
package com.tyron.code.language.java; import androidx.annotation.NonNull; import com.google.common.collect.Ordering; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ErroneousTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.JavacTask; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreePathScanner; import com.sun.source.util.Trees; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeInfo; import com.tyron.code.analyzer.semantic.SemanticToken; import com.tyron.code.analyzer.semantic.TokenType; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; public class JavaSemanticHighlighter extends TreePathScanner<Void, Boolean> { private static final Ordering<SemanticToken> INCREASING = Ordering.from(Comparator.comparingInt(SemanticToken::getOffset)); private JCTree.JCCompilationUnit cu; private SourcePositions pos; private final Trees trees; private final Elements elements; private List<SemanticToken> tokens; public JavaSemanticHighlighter(JavacTask task) { this.trees = Trees.instance(task); this.pos = trees.getSourcePositions(); this.elements = task.getElements(); this.tokens = new ArrayList<>(); } private enum TokenModifier { ABSTRACT("abstract"), STATIC("static"), FINAL("readOnly"), DECLARATION("declaration"), PUBLIC("public"), PRIVATE("private"), PROTECTED("protected"), NATIVE("native"), GENERIC("generic"), TYPE_ARGUMENT("typeArgument"), IMPORT_DECLARATION("importDeclaration"), CONSTRUCTOR("constructor"); private final String genericName; /** * The bitmask for this semantic token modifier. Use bitwise OR to combine with other token * modifiers. */ public final int bitmask = 1 << ordinal(); /** * The inverse bitmask for this semantic token modifier. Use bitwise AND to remove from other * token modifiers. */ public final int inverseBitmask = ~bitmask; TokenModifier(String genericName) { this.genericName = genericName; } @NonNull @Override public String toString() { return genericName; } /** * Returns the bitwise OR of all the semantic token modifiers that apply based on the binding's * {@link Modifier}s and wheter or not it is deprecated. * * @param binding A binding. * @return The bitwise OR of the applicable modifiers for the binding. */ public static int checkJavaModifiers(Element binding) { if (binding == null) { return 0; } int modifiers = 0; Set<Modifier> bindingModifiers = binding.getModifiers(); if (bindingModifiers.contains(Modifier.PUBLIC)) { modifiers |= PUBLIC.bitmask; } if (bindingModifiers.contains(Modifier.PRIVATE)) { modifiers |= PRIVATE.bitmask; } if (bindingModifiers.contains(Modifier.PROTECTED)) { modifiers |= PROTECTED.bitmask; } if (bindingModifiers.contains(Modifier.ABSTRACT)) { modifiers |= ABSTRACT.bitmask; } if (bindingModifiers.contains(Modifier.STATIC)) { modifiers |= STATIC.bitmask; } if (bindingModifiers.contains(Modifier.FINAL)) { modifiers |= FINAL.bitmask; } if (bindingModifiers.contains(Modifier.NATIVE)) { modifiers |= NATIVE.bitmask; } // if (binding.isDeprecated()) { // modifiers |= DEPRECATED.bitmask; // } return modifiers; } } public List<SemanticToken> getTokens() { return INCREASING.immutableSortedCopy(tokens); } private void addToken(int offset, int length, TokenType tokenType, int modifiers) { tokens.add(new SemanticToken(offset, length, tokenType, modifiers)); } private void addToken(JCTree node, TokenType tokenType, int modifiers) { addToken(node.getStartPosition(), node.getStartPosition(), tokenType, modifiers); } @Override public Void visitCompilationUnit(CompilationUnitTree t, Boolean b) { cu = (JCTree.JCCompilationUnit) t; return super.visitCompilationUnit(t, b); } @Override public Void visitIdentifier(IdentifierTree t, Boolean b) { JCTree.JCIdent identifier = ((JCTree.JCIdent) t); Tree parent = getCurrentPath().getParentPath().getLeaf(); Tree.Kind parentKind = parent.getKind(); switch (parentKind) { case ANNOTATION: addAnnotation(identifier); break; case VARIABLE: addVariable(identifier); break; case MEMBER_SELECT: addMemberSelect(identifier); break; default: addIdentifier(identifier); } return super.visitIdentifier(t, b); } private void addMemberSelect(JCTree.JCIdent identifier) { Element element = trees.getElement(getCurrentPath()); TokenType applicableType = JavaTokenTypes.getApplicableType(element); if (applicableType == null) { return; } int start = (int) pos.getStartPosition(cu, identifier); int end = (int) pos.getEndPosition(cu, identifier); addToken(start, end - start, applicableType, 0); } private void addVariable(JCTree.JCIdent identifier) { int start = identifier.getStartPosition(); int end = start + identifier.getName().length(); Element element = trees.getElement(getCurrentPath()); addToken(start, end - start, JavaTokenTypes.CLASS, 0); } private void addIdentifier(JCTree.JCIdent identifier) { if (identifier == null) { return; } int start = identifier.getStartPosition(); int end = start + identifier.getName().length(); } private void addAnnotation(JCTree.JCIdent identifier) { TokenType tokenType = TokenType.UNKNOWN; Element element = trees.getElement(getCurrentPath()); if (element != null) { TypeMirror type = element.asType(); if (type.getKind() != TypeKind.ERROR) { tokenType = JavaTokenTypes.ANNOTATION; } } int start = identifier.getStartPosition(); int end = (int) pos.getEndPosition(cu, identifier); addToken(start, end - start, tokenType, 0); } @Override public Void visitClass(ClassTree t, Boolean b) { Element element = trees.getElement(getCurrentPath()); if (element == null) { return super.visitClass(t, b); } int start = (int) pos.getStartPosition(cu, t); String contents = getContents(); start = contents.indexOf(element.getSimpleName().toString(), start); if (start == -1) { return super.visitClass(t, b); } int end = start + element.getSimpleName().length(); TokenType applicableType = JavaTokenTypes.getApplicableType(element); if (applicableType != null) { addToken(start, end - start, applicableType, TokenModifier.checkJavaModifiers(element)); } return super.visitClass(t, b); } @Override public Void visitMethod(MethodTree methodTree, Boolean aBoolean) { Element element = trees.getElement(getCurrentPath()); if (element == null) { return super.visitMethod(methodTree, aBoolean); } boolean isConstructor = TreeInfo.isConstructor((JCTree) methodTree); String name; if (isConstructor) { name = element.getEnclosingElement().getSimpleName().toString(); } else { name = element.getSimpleName().toString(); } String contents = getContents(); int start = (int) pos.getStartPosition(cu, methodTree); start = contents.indexOf(name, start); int end = start + name.length(); long realEnd = pos.getEndPosition(cu, methodTree); if (realEnd != -1) { TokenType type; if (isConstructor) { type = JavaTokenTypes.CONSTRUCTOR; } else { type = JavaTokenTypes.METHOD_DECLARATION; } addToken(start, end - start, type, 0); } return super.visitMethod(methodTree, aBoolean); } @Override public Void visitVariable(VariableTree t, Boolean b) { JCTree tree = ((JCTree.JCVariableDecl) t); int start = tree.getPreferredPosition(); int end = start + t.getName().length(); Element element = trees.getElement(getCurrentPath()); TokenType applicableType = JavaTokenTypes.getApplicableType(element); if (applicableType != null) { if (element.getModifiers().contains(Modifier.FINAL)) { addToken( start, end - start, JavaTokenTypes.CONSTANT, TokenModifier.checkJavaModifiers(element)); } else { addToken(start, end - start, applicableType, TokenModifier.checkJavaModifiers(element)); } } return super.visitVariable(t, b); } private void addSuper() {} @Override public Void visitMethodInvocation(MethodInvocationTree t, Boolean b) { JCTree.JCMethodInvocation method = ((JCTree.JCMethodInvocation) t); Element element = trees.getElement(getCurrentPath()); int end = method.getPreferredPosition(); int realEndPosition = (int) pos.getEndPosition(cu, t); if (end == -1 || element == null || realEndPosition == -1) { return super.visitMethodInvocation(t, b); } int start = end - element.getSimpleName().length(); TokenType type = JavaTokenTypes.METHOD_CALL; if (element.getKind() == ElementKind.CONSTRUCTOR) { start = method.getStartPosition(); end = start + "super".length(); type = JavaTokenTypes.CONSTRUCTOR; } addToken(start, end - start, type, TokenModifier.checkJavaModifiers(element)); return super.visitMethodInvocation(t, b); } @Override public Void visitErroneous(ErroneousTree t, Boolean b) { List<? extends Tree> errorTrees = t.getErrorTrees(); if (errorTrees != null) { for (Tree errorTree : errorTrees) { scan(errorTree, b); } } return null; } private String getContents() { try { return String.valueOf(cu.getSourceFile().getCharContent(false)); } catch (IOException e) { return ""; } } }
10,480
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaTokenTypes.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/java/JavaTokenTypes.java
package com.tyron.code.language.java; import com.sun.tools.javac.code.Symbol; import com.tyron.code.analyzer.semantic.TokenType; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.VariableElement; public class JavaTokenTypes { public static final TokenType FIELD = TokenType.create("variable.other.object.property.java"); public static final TokenType CONSTANT = TokenType.create("variable.other.constant"); public static final TokenType PARAMETER = TokenType.create("variable.parameter"); public static final TokenType CLASS = TokenType.create("entity.name.type.class"); public static final TokenType METHOD_CALL = TokenType.create("meta.method-call"); public static final TokenType METHOD_DECLARATION = TokenType.create("entity.name.function.member"); public static final TokenType VARIABLE = TokenType.create("entity.name.variable"); public static final TokenType CONSTRUCTOR = TokenType.create("class.instance.constructor"); public static final TokenType ANNOTATION = TokenType.create("storage.type.annotation"); public static TokenType getApplicableType(Element element) { if (element == null) { return null; } switch (element.getKind()) { case LOCAL_VARIABLE: Symbol.VarSymbol varSymbol = (Symbol.VarSymbol) element; if (varSymbol.getModifiers().contains(Modifier.FINAL)) { return CONSTANT; } return VARIABLE; case METHOD: Symbol.MethodSymbol methodSymbol = ((Symbol.MethodSymbol) element); if (methodSymbol.isConstructor()) { return getApplicableType(methodSymbol.getEnclosingElement()); } return METHOD_DECLARATION; case FIELD: VariableElement variableElement = ((VariableElement) element); if (variableElement.getModifiers().contains(Modifier.FINAL)) { return CONSTANT; } return FIELD; case CLASS: return CLASS; case CONSTRUCTOR: return CONSTRUCTOR; case PARAMETER: return PARAMETER; case ANNOTATION_TYPE: return ANNOTATION; default: return null; } } }
2,195
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Json.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/Json.java
package com.tyron.code.language.json; import com.tyron.code.language.Language; import com.tyron.editor.Editor; import java.io.File; public class Json implements Language { @Override public boolean isApplicable(File ext) { return ext.getName().endsWith(".json"); } @Override public io.github.rosemoe.sora.lang.Language get(Editor editor) { return new JsonLanguage(editor); } }
399
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JSONListener.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/JSONListener.java
// Generated from // /home/tyron/AndroidStudioProjects/CodeAssist/app/src/main/java/com/tyron/code/ui/editor/language/json/JSON.g4 by ANTLR 4.9.2 package com.tyron.code.language.json; import org.antlr.v4.runtime.tree.ParseTreeListener; /** This interface defines a complete listener for a parse tree produced by {@link JSONParser}. */ public interface JSONListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link JSONParser#json}. * * @param ctx the parse tree */ void enterJson(JSONParser.JsonContext ctx); /** * Exit a parse tree produced by {@link JSONParser#json}. * * @param ctx the parse tree */ void exitJson(JSONParser.JsonContext ctx); /** * Enter a parse tree produced by {@link JSONParser#obj}. * * @param ctx the parse tree */ void enterObj(JSONParser.ObjContext ctx); /** * Exit a parse tree produced by {@link JSONParser#obj}. * * @param ctx the parse tree */ void exitObj(JSONParser.ObjContext ctx); /** * Enter a parse tree produced by {@link JSONParser#pair}. * * @param ctx the parse tree */ void enterPair(JSONParser.PairContext ctx); /** * Exit a parse tree produced by {@link JSONParser#pair}. * * @param ctx the parse tree */ void exitPair(JSONParser.PairContext ctx); /** * Enter a parse tree produced by {@link JSONParser#arr}. * * @param ctx the parse tree */ void enterArr(JSONParser.ArrContext ctx); /** * Exit a parse tree produced by {@link JSONParser#arr}. * * @param ctx the parse tree */ void exitArr(JSONParser.ArrContext ctx); /** * Enter a parse tree produced by {@link JSONParser#value}. * * @param ctx the parse tree */ void enterValue(JSONParser.ValueContext ctx); /** * Exit a parse tree produced by {@link JSONParser#value}. * * @param ctx the parse tree */ void exitValue(JSONParser.ValueContext ctx); }
1,940
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JSONBaseListener.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/JSONBaseListener.java
// Generated from // /home/tyron/AndroidStudioProjects/CodeAssist/app/src/main/java/com/tyron/code/ui/editor/language/json/JSON.g4 by ANTLR 4.9.2 package com.tyron.code.language.json; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link JSONListener}, which can be extended to * create a listener which only needs to handle a subset of the available methods. */ public class JSONBaseListener implements JSONListener { /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void enterJson(JSONParser.JsonContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void exitJson(JSONParser.JsonContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void enterObj(JSONParser.ObjContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void exitObj(JSONParser.ObjContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void enterPair(JSONParser.PairContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void exitPair(JSONParser.PairContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void enterArr(JSONParser.ArrContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void exitArr(JSONParser.ArrContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void enterValue(JSONParser.ValueContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void exitValue(JSONParser.ValueContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void enterEveryRule(ParserRuleContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void exitEveryRule(ParserRuleContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void visitTerminal(TerminalNode node) {} /** * {@inheritDoc} * * <p>The default implementation does nothing. */ @Override public void visitErrorNode(ErrorNode node) {} }
2,689
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JSONVisitor.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/JSONVisitor.java
// Generated from // /home/tyron/AndroidStudioProjects/CodeAssist/app/src/main/java/com/tyron/code/ui/editor/language/json/JSON.g4 by ANTLR 4.9.2 package com.tyron.code.language.json; import org.antlr.v4.runtime.tree.ParseTreeVisitor; /** * This interface defines a complete generic visitor for a parse tree produced by {@link * JSONParser}. * * @param <T> The return type of the visit operation. Use {@link Void} for operations with no return * type. */ public interface JSONVisitor<T> extends ParseTreeVisitor<T> { /** * Visit a parse tree produced by {@link JSONParser#json}. * * @param ctx the parse tree * @return the visitor result */ T visitJson(JSONParser.JsonContext ctx); /** * Visit a parse tree produced by {@link JSONParser#obj}. * * @param ctx the parse tree * @return the visitor result */ T visitObj(JSONParser.ObjContext ctx); /** * Visit a parse tree produced by {@link JSONParser#pair}. * * @param ctx the parse tree * @return the visitor result */ T visitPair(JSONParser.PairContext ctx); /** * Visit a parse tree produced by {@link JSONParser#arr}. * * @param ctx the parse tree * @return the visitor result */ T visitArr(JSONParser.ArrContext ctx); /** * Visit a parse tree produced by {@link JSONParser#value}. * * @param ctx the parse tree * @return the visitor result */ T visitValue(JSONParser.ValueContext ctx); }
1,452
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JsonAnalyzer.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/JsonAnalyzer.java
package com.tyron.code.language.json; import com.tyron.code.language.AbstractCodeAnalyzer; import io.github.rosemoe.sora.lang.styling.CodeBlock; import io.github.rosemoe.sora.lang.styling.MappedSpans; import io.github.rosemoe.sora.lang.styling.Styles; import io.github.rosemoe.sora.widget.schemes.EditorColorScheme; import java.util.Stack; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Token; public class JsonAnalyzer extends AbstractCodeAnalyzer<Object> { private final Stack<CodeBlock> mBlockLines = new Stack<>(); private int mMaxSwitch; private int mCurrSwitch; @Override public Lexer getLexer(CharStream input) { return new JSONLexer(input); } @Override public void setup() { putColor( EditorColorScheme.TEXT_NORMAL, JSONLexer.LBRACKET, JSONLexer.RBRACKET, JSONLexer.LBRACE, JSONLexer.RBRACE); putColor( EditorColorScheme.KEYWORD, JSONLexer.TRUE, JSONLexer.FALSE, JSONLexer.NULL, JSONLexer.COLON, JSONLexer.COMMA); putColor(EditorColorScheme.OPERATOR, JSONLexer.COLON); putColor(EditorColorScheme.LITERAL, JSONLexer.NUMBER); putColor(EditorColorScheme.ATTRIBUTE_NAME, JSONLexer.STRING); } @Override public void analyzeInBackground(CharSequence contents) {} @Override protected void beforeAnalyze() { mBlockLines.clear(); mMaxSwitch = 1; mCurrSwitch = 0; } @Override public boolean onNextToken(Token currentToken, Styles styles, MappedSpans.Builder colors) { int line = currentToken.getLine() - 1; int column = currentToken.getCharPositionInLine(); switch (currentToken.getType()) { case JSONLexer.STRING: Token previousToken = getPreviousToken(); if (previousToken != null) { if (previousToken.getType() == JSONLexer.COLON) { colors.addIfNeeded(line, column, EditorColorScheme.LITERAL); return true; } } break; case JSONLexer.RBRACE: if (!mBlockLines.isEmpty()) { CodeBlock b = mBlockLines.pop(); b.endLine = line; b.endColumn = column; if (b.startLine != b.endLine) { styles.addCodeBlock(b); } } return false; case JSONLexer.LBRACE: if (mBlockLines.isEmpty()) { if (mCurrSwitch > mMaxSwitch) { mMaxSwitch = mCurrSwitch; } mCurrSwitch = 0; } mCurrSwitch++; CodeBlock block = styles.obtainNewBlock(); block.startLine = line; block.startColumn = column; mBlockLines.push(block); return false; } return false; } @Override protected void afterAnalyze(CharSequence content, Styles styles, MappedSpans.Builder colors) { if (mBlockLines.isEmpty()) { if (mMaxSwitch > mCurrSwitch) { mMaxSwitch = mCurrSwitch; } } styles.setSuppressSwitch(mMaxSwitch + 10); } }
3,027
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JSONLexer.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/JSONLexer.java
// Generated from // /home/tyron/AndroidStudioProjects/CodeAssist/app/src/main/java/com/tyron/code/ui/editor/language/json/JSON.g4 by ANTLR 4.9.2 package com.tyron.code.language.json; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class JSONLexer extends Lexer { static { RuntimeMetaData.checkVersion("4.9.2", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int TRUE = 1, FALSE = 2, NULL = 3, COLON = 4, STRING = 5, LBRACE = 6, RBRACE = 7, LBRACKET = 8, RBRACKET = 9, COMMA = 10, NUMBER = 11, WS = 12; public static String[] channelNames = {"DEFAULT_TOKEN_CHANNEL", "HIDDEN"}; public static String[] modeNames = {"DEFAULT_MODE"}; private static String[] makeRuleNames() { return new String[] { "TRUE", "FALSE", "NULL", "COLON", "STRING", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "COMMA", "ESC", "UNICODE", "HEX", "SAFECODEPOINT", "NUMBER", "INT", "EXP", "WS" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, "'true'", "'false'", "'null'", "':'", null, "'{'", "'}'", "'['", "']'", "','" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, "TRUE", "FALSE", "NULL", "COLON", "STRING", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "COMMA", "NUMBER", "WS" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public JSONLexer(CharStream input) { super(input); _interp = new LexerATNSimulator(this, _ATN, _decisionToDFA, _sharedContextCache); } @Override public String getGrammarFileName() { return "JSON.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\16\u0082\b\1\4\2" + "\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4" + "\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22" + "\t\22\4\23\t\23\3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3" + "\4\3\4\3\4\3\5\3\5\3\6\3\6\3\6\7\6=\n\6\f\6\16\6@\13\6\3\6\3\6\3\7\3\7" + "\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\f\5\fQ\n\f\3\r\3\r\3\r\3" + "\r\3\r\3\r\3\16\3\16\3\17\3\17\3\20\5\20^\n\20\3\20\3\20\3\20\6\20c\n" + "\20\r\20\16\20d\5\20g\n\20\3\20\5\20j\n\20\3\21\3\21\3\21\7\21o\n\21\f" + "\21\16\21r\13\21\5\21t\n\21\3\22\3\22\5\22x\n\22\3\22\3\22\3\23\6\23}" + "\n\23\r\23\16\23~\3\23\3\23\2\2\24\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n" + "\23\13\25\f\27\2\31\2\33\2\35\2\37\r!\2#\2%\16\3\2\n\n\2$$\61\61^^ddh" + "hppttvv\5\2\62;CHch\5\2\2!$$^^\3\2\62;\3\2\63;\4\2GGgg\4\2--//\5\2\13" + "\f\17\17\"\"\2\u0086\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2" + "\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3" + "\2\2\2\2\37\3\2\2\2\2%\3\2\2\2\3\'\3\2\2\2\5,\3\2\2\2\7\62\3\2\2\2\t\67" + "\3\2\2\2\139\3\2\2\2\rC\3\2\2\2\17E\3\2\2\2\21G\3\2\2\2\23I\3\2\2\2\25" + "K\3\2\2\2\27M\3\2\2\2\31R\3\2\2\2\33X\3\2\2\2\35Z\3\2\2\2\37]\3\2\2\2" + "!s\3\2\2\2#u\3\2\2\2%|\3\2\2\2\'(\7v\2\2()\7t\2\2)*\7w\2\2*+\7g\2\2+\4" + "\3\2\2\2,-\7h\2\2-.\7c\2\2./\7n\2\2/\60\7u\2\2\60\61\7g\2\2\61\6\3\2\2" + "\2\62\63\7p\2\2\63\64\7w\2\2\64\65\7n\2\2\65\66\7n\2\2\66\b\3\2\2\2\67" + "8\7<\2\28\n\3\2\2\29>\7$\2\2:=\5\27\f\2;=\5\35\17\2<:\3\2\2\2<;\3\2\2" + "\2=@\3\2\2\2><\3\2\2\2>?\3\2\2\2?A\3\2\2\2@>\3\2\2\2AB\7$\2\2B\f\3\2\2" + "\2CD\7}\2\2D\16\3\2\2\2EF\7\177\2\2F\20\3\2\2\2GH\7]\2\2H\22\3\2\2\2I" + "J\7_\2\2J\24\3\2\2\2KL\7.\2\2L\26\3\2\2\2MP\7^\2\2NQ\t\2\2\2OQ\5\31\r" + "\2PN\3\2\2\2PO\3\2\2\2Q\30\3\2\2\2RS\7w\2\2ST\5\33\16\2TU\5\33\16\2UV" + "\5\33\16\2VW\5\33\16\2W\32\3\2\2\2XY\t\3\2\2Y\34\3\2\2\2Z[\n\4\2\2[\36" + "\3\2\2\2\\^\7/\2\2]\\\3\2\2\2]^\3\2\2\2^_\3\2\2\2_f\5!\21\2`b\7\60\2\2" + "ac\t\5\2\2ba\3\2\2\2cd\3\2\2\2db\3\2\2\2de\3\2\2\2eg\3\2\2\2f`\3\2\2\2" + "fg\3\2\2\2gi\3\2\2\2hj\5#\22\2ih\3\2\2\2ij\3\2\2\2j \3\2\2\2kt\7\62\2" + "\2lp\t\6\2\2mo\t\5\2\2nm\3\2\2\2or\3\2\2\2pn\3\2\2\2pq\3\2\2\2qt\3\2\2" + "\2rp\3\2\2\2sk\3\2\2\2sl\3\2\2\2t\"\3\2\2\2uw\t\7\2\2vx\t\b\2\2wv\3\2" + "\2\2wx\3\2\2\2xy\3\2\2\2yz\5!\21\2z$\3\2\2\2{}\t\t\2\2|{\3\2\2\2}~\3\2" + "\2\2~|\3\2\2\2~\177\3\2\2\2\177\u0080\3\2\2\2\u0080\u0081\b\23\2\2\u0081" + "&\3\2\2\2\16\2<>P]dfipsw~\3\b\2\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
6,607
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JsonLanguage.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/JsonLanguage.java
package com.tyron.code.language.json; import android.annotation.SuppressLint; import android.content.res.AssetManager; import android.os.Bundle; import androidx.annotation.NonNull; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; import com.tyron.code.ApplicationLoader; import com.tyron.code.analyzer.BaseTextmateAnalyzer; import com.tyron.code.ui.editor.impl.text.rosemoe.CodeEditorView; import com.tyron.editor.Editor; import io.github.rosemoe.sora.lang.Language; import io.github.rosemoe.sora.lang.analysis.AnalyzeManager; import io.github.rosemoe.sora.lang.completion.CompletionCancelledException; import io.github.rosemoe.sora.lang.completion.CompletionPublisher; import io.github.rosemoe.sora.lang.smartEnter.NewlineHandleResult; import io.github.rosemoe.sora.lang.smartEnter.NewlineHandler; import io.github.rosemoe.sora.langs.textmate.theme.TextMateColorScheme; import io.github.rosemoe.sora.text.CharPosition; import io.github.rosemoe.sora.text.ContentReference; import io.github.rosemoe.sora.text.TextUtils; import io.github.rosemoe.sora.widget.SymbolPairMatch; import java.io.InputStreamReader; import java.io.StringWriter; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.Token; public class JsonLanguage implements Language { private final Editor mEditor; private final BaseTextmateAnalyzer mAnalyzer; public JsonLanguage(Editor editor) { mEditor = editor; try { AssetManager assetManager = ApplicationLoader.applicationContext.getAssets(); mAnalyzer = new BaseTextmateAnalyzer( editor, "json.tmLanguage.json", assetManager.open("textmate/json" + "/syntaxes/json" + ".tmLanguage.json"), new InputStreamReader(assetManager.open("textmate/json/language-configuration.json")), ((TextMateColorScheme) ((CodeEditorView) editor).getColorScheme()).getRawTheme()); } catch (Exception e) { throw new RuntimeException(e); } } @NonNull @Override public AnalyzeManager getAnalyzeManager() { return mAnalyzer; } @Override public int getInterruptionLevel() { return INTERRUPTION_LEVEL_STRONG; } @Override public void requireAutoComplete( @NonNull ContentReference content, @NonNull CharPosition position, @NonNull CompletionPublisher publisher, @NonNull Bundle extraArguments) throws CompletionCancelledException {} public int getTabWidth() { return 2; } @Override public int getIndentAdvance(@NonNull ContentReference content, int line, int column) { String text = content.getLine(line).substring(0, column); return getIndentAdvance(text); } private int getIndentAdvance(String content) { JSONLexer lexer = new JSONLexer(CharStreams.fromString(content)); Token token; int advance = 0; while ((token = lexer.nextToken()).getType() != Token.EOF) { int type = token.getType(); if (type == JSONLexer.LBRACKET || type == JSONLexer.LBRACE) { advance++; } } advance = Math.max(0, advance); return advance * getTabWidth(); } @Override public boolean useTab() { return true; } @SuppressLint("WrongThread") @Override public CharSequence format(CharSequence text) { try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); try (StringWriter writer = new StringWriter()) { JsonWriter jsonWriter = gson.newJsonWriter(writer); jsonWriter.setIndent(useTab() ? "\t" : " "); gson.toJson(JsonParser.parseString(text.toString()), jsonWriter); return writer.toString(); } } catch (Throwable e) { // format error, return the original string return text; } } @Override public SymbolPairMatch getSymbolPairs() { return new SymbolPairMatch.DefaultSymbolPairs(); } @Override public NewlineHandler[] getNewlineHandlers() { return new NewlineHandler[] {new IndentHandler("{", "}"), new IndentHandler("[", "]")}; } @Override public void destroy() {} class IndentHandler implements NewlineHandler { private final String start; private final String end; public IndentHandler(String start, String end) { this.start = start; this.end = end; } @Override public boolean matchesRequirement(String beforeText, String afterText) { return beforeText.endsWith(start) && afterText.startsWith(end); } @Override public NewlineHandleResult handleNewline(String beforeText, String afterText, int tabSize) { int count = TextUtils.countLeadingSpaceCount(beforeText, tabSize); int advanceBefore = getIndentAdvance(beforeText); int advanceAfter = getIndentAdvance(afterText); String text; StringBuilder sb = new StringBuilder("\n") .append(TextUtils.createIndent(count + advanceBefore, tabSize, useTab())) .append('\n') .append(text = TextUtils.createIndent(count + advanceAfter, tabSize, useTab())); int shiftLeft = text.length() + 1; return new NewlineHandleResult(sb, shiftLeft); } } }
5,216
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JSONParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/JSONParser.java
// Generated from // /home/tyron/AndroidStudioProjects/CodeAssist/app/src/main/java/com/tyron/code/ui/editor/language/json/JSON.g4 by ANTLR 4.9.2 package com.tyron.code.language.json; import java.util.List; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.tree.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class JSONParser extends Parser { static { RuntimeMetaData.checkVersion("4.9.2", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int TRUE = 1, FALSE = 2, NULL = 3, COLON = 4, STRING = 5, LBRACE = 6, RBRACE = 7, LBRACKET = 8, RBRACKET = 9, COMMA = 10, NUMBER = 11, WS = 12; public static final int RULE_json = 0, RULE_obj = 1, RULE_pair = 2, RULE_arr = 3, RULE_value = 4; private static String[] makeRuleNames() { return new String[] {"json", "obj", "pair", "arr", "value"}; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, "'true'", "'false'", "'null'", "':'", null, "'{'", "'}'", "'['", "']'", "','" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, "TRUE", "FALSE", "NULL", "COLON", "STRING", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "COMMA", "NUMBER", "WS" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "JSON.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public JSONParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this, _ATN, _decisionToDFA, _sharedContextCache); } public static class JsonContext extends ParserRuleContext { public ValueContext value() { return getRuleContext(ValueContext.class, 0); } public JsonContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_json; } @Override public void enterRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).enterJson(this); } @Override public void exitRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).exitJson(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof JSONVisitor) return ((JSONVisitor<? extends T>) visitor).visitJson(this); else return visitor.visitChildren(this); } } public final JsonContext json() throws RecognitionException { JsonContext _localctx = new JsonContext(_ctx, getState()); enterRule(_localctx, 0, RULE_json); try { enterOuterAlt(_localctx, 1); { setState(10); value(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ObjContext extends ParserRuleContext { public TerminalNode LBRACE() { return getToken(JSONParser.LBRACE, 0); } public List<PairContext> pair() { return getRuleContexts(PairContext.class); } public PairContext pair(int i) { return getRuleContext(PairContext.class, i); } public TerminalNode RBRACE() { return getToken(JSONParser.RBRACE, 0); } public List<TerminalNode> COMMA() { return getTokens(JSONParser.COMMA); } public TerminalNode COMMA(int i) { return getToken(JSONParser.COMMA, i); } public ObjContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_obj; } @Override public void enterRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).enterObj(this); } @Override public void exitRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).exitObj(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof JSONVisitor) return ((JSONVisitor<? extends T>) visitor).visitObj(this); else return visitor.visitChildren(this); } } public final ObjContext obj() throws RecognitionException { ObjContext _localctx = new ObjContext(_ctx, getState()); enterRule(_localctx, 2, RULE_obj); int _la; try { setState(25); _errHandler.sync(this); switch (getInterpreter().adaptivePredict(_input, 1, _ctx)) { case 1: enterOuterAlt(_localctx, 1); { setState(12); match(LBRACE); setState(13); pair(); setState(18); _errHandler.sync(this); _la = _input.LA(1); while (_la == COMMA) { { { setState(14); match(COMMA); setState(15); pair(); } } setState(20); _errHandler.sync(this); _la = _input.LA(1); } setState(21); match(RBRACE); } break; case 2: enterOuterAlt(_localctx, 2); { setState(23); match(LBRACE); setState(24); match(RBRACE); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class PairContext extends ParserRuleContext { public TerminalNode STRING() { return getToken(JSONParser.STRING, 0); } public TerminalNode COLON() { return getToken(JSONParser.COLON, 0); } public ValueContext value() { return getRuleContext(ValueContext.class, 0); } public PairContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_pair; } @Override public void enterRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).enterPair(this); } @Override public void exitRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).exitPair(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof JSONVisitor) return ((JSONVisitor<? extends T>) visitor).visitPair(this); else return visitor.visitChildren(this); } } public final PairContext pair() throws RecognitionException { PairContext _localctx = new PairContext(_ctx, getState()); enterRule(_localctx, 4, RULE_pair); try { enterOuterAlt(_localctx, 1); { setState(27); match(STRING); setState(28); match(COLON); setState(29); value(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ArrContext extends ParserRuleContext { public TerminalNode LBRACKET() { return getToken(JSONParser.LBRACKET, 0); } public List<ValueContext> value() { return getRuleContexts(ValueContext.class); } public ValueContext value(int i) { return getRuleContext(ValueContext.class, i); } public TerminalNode RBRACKET() { return getToken(JSONParser.RBRACKET, 0); } public List<TerminalNode> COMMA() { return getTokens(JSONParser.COMMA); } public TerminalNode COMMA(int i) { return getToken(JSONParser.COMMA, i); } public ArrContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_arr; } @Override public void enterRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).enterArr(this); } @Override public void exitRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).exitArr(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof JSONVisitor) return ((JSONVisitor<? extends T>) visitor).visitArr(this); else return visitor.visitChildren(this); } } public final ArrContext arr() throws RecognitionException { ArrContext _localctx = new ArrContext(_ctx, getState()); enterRule(_localctx, 6, RULE_arr); int _la; try { setState(44); _errHandler.sync(this); switch (getInterpreter().adaptivePredict(_input, 3, _ctx)) { case 1: enterOuterAlt(_localctx, 1); { setState(31); match(LBRACKET); setState(32); value(); setState(37); _errHandler.sync(this); _la = _input.LA(1); while (_la == COMMA) { { { setState(33); match(COMMA); setState(34); value(); } } setState(39); _errHandler.sync(this); _la = _input.LA(1); } setState(40); match(RBRACKET); } break; case 2: enterOuterAlt(_localctx, 2); { setState(42); match(LBRACKET); setState(43); match(RBRACKET); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ValueContext extends ParserRuleContext { public TerminalNode STRING() { return getToken(JSONParser.STRING, 0); } public TerminalNode NUMBER() { return getToken(JSONParser.NUMBER, 0); } public ObjContext obj() { return getRuleContext(ObjContext.class, 0); } public ArrContext arr() { return getRuleContext(ArrContext.class, 0); } public TerminalNode TRUE() { return getToken(JSONParser.TRUE, 0); } public TerminalNode FALSE() { return getToken(JSONParser.FALSE, 0); } public TerminalNode NULL() { return getToken(JSONParser.NULL, 0); } public ValueContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_value; } @Override public void enterRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).enterValue(this); } @Override public void exitRule(ParseTreeListener listener) { if (listener instanceof JSONListener) ((JSONListener) listener).exitValue(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof JSONVisitor) return ((JSONVisitor<? extends T>) visitor).visitValue(this); else return visitor.visitChildren(this); } } public final ValueContext value() throws RecognitionException { ValueContext _localctx = new ValueContext(_ctx, getState()); enterRule(_localctx, 8, RULE_value); try { setState(53); _errHandler.sync(this); switch (_input.LA(1)) { case STRING: enterOuterAlt(_localctx, 1); { setState(46); match(STRING); } break; case NUMBER: enterOuterAlt(_localctx, 2); { setState(47); match(NUMBER); } break; case LBRACE: enterOuterAlt(_localctx, 3); { setState(48); obj(); } break; case LBRACKET: enterOuterAlt(_localctx, 4); { setState(49); arr(); } break; case TRUE: enterOuterAlt(_localctx, 5); { setState(50); match(TRUE); } break; case FALSE: enterOuterAlt(_localctx, 6); { setState(51); match(FALSE); } break; case NULL: enterOuterAlt(_localctx, 7); { setState(52); match(NULL); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\16:\4\2\t\2\4\3\t" + "\3\4\4\t\4\4\5\t\5\4\6\t\6\3\2\3\2\3\3\3\3\3\3\3\3\7\3\23\n\3\f\3\16\3" + "\26\13\3\3\3\3\3\3\3\3\3\5\3\34\n\3\3\4\3\4\3\4\3\4\3\5\3\5\3\5\3\5\7" + "\5&\n\5\f\5\16\5)\13\5\3\5\3\5\3\5\3\5\5\5/\n\5\3\6\3\6\3\6\3\6\3\6\3" + "\6\3\6\5\68\n\6\3\6\2\2\7\2\4\6\b\n\2\2\2>\2\f\3\2\2\2\4\33\3\2\2\2\6" + "\35\3\2\2\2\b.\3\2\2\2\n\67\3\2\2\2\f\r\5\n\6\2\r\3\3\2\2\2\16\17\7\b" + "\2\2\17\24\5\6\4\2\20\21\7\f\2\2\21\23\5\6\4\2\22\20\3\2\2\2\23\26\3\2" + "\2\2\24\22\3\2\2\2\24\25\3\2\2\2\25\27\3\2\2\2\26\24\3\2\2\2\27\30\7\t" + "\2\2\30\34\3\2\2\2\31\32\7\b\2\2\32\34\7\t\2\2\33\16\3\2\2\2\33\31\3\2" + "\2\2\34\5\3\2\2\2\35\36\7\7\2\2\36\37\7\6\2\2\37 \5\n\6\2 \7\3\2\2\2!" + "\"\7\n\2\2\"\'\5\n\6\2#$\7\f\2\2$&\5\n\6\2%#\3\2\2\2&)\3\2\2\2\'%\3\2" + "\2\2\'(\3\2\2\2(*\3\2\2\2)\'\3\2\2\2*+\7\13\2\2+/\3\2\2\2,-\7\n\2\2-/" + "\7\13\2\2.!\3\2\2\2.,\3\2\2\2/\t\3\2\2\2\608\7\7\2\2\618\7\r\2\2\628\5" + "\4\3\2\638\5\b\5\2\648\7\3\2\2\658\7\4\2\2\668\7\5\2\2\67\60\3\2\2\2\67" + "\61\3\2\2\2\67\62\3\2\2\2\67\63\3\2\2\2\67\64\3\2\2\2\67\65\3\2\2\2\67" + "\66\3\2\2\28\13\3\2\2\2\7\24\33\'.\67"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
16,319
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JSONBaseVisitor.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/json/JSONBaseVisitor.java
// Generated from // /home/tyron/AndroidStudioProjects/CodeAssist/app/src/main/java/com/tyron/code/ui/editor/language/json/JSON.g4 by ANTLR 4.9.2 package com.tyron.code.language.json; import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor; /** * This class provides an empty implementation of {@link JSONVisitor}, which can be extended to * create a visitor which only needs to handle a subset of the available methods. * * @param <T> The return type of the visit operation. Use {@link Void} for operations with no return * type. */ public class JSONBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements JSONVisitor<T> { /** * {@inheritDoc} * * <p>The default implementation returns the result of calling {@link #visitChildren} on {@code * ctx}. */ @Override public T visitJson(JSONParser.JsonContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling {@link #visitChildren} on {@code * ctx}. */ @Override public T visitObj(JSONParser.ObjContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling {@link #visitChildren} on {@code * ctx}. */ @Override public T visitPair(JSONParser.PairContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling {@link #visitChildren} on {@code * ctx}. */ @Override public T visitArr(JSONParser.ArrContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling {@link #visitChildren} on {@code * ctx}. */ @Override public T visitValue(JSONParser.ValueContext ctx) { return visitChildren(ctx); } }
1,863
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BaseIncrementalAnalyzeManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/textmate/BaseIncrementalAnalyzeManager.java
package com.tyron.code.language.textmate; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.github.rosemoe.sora.lang.analysis.IncrementalAnalyzeManager; import io.github.rosemoe.sora.lang.analysis.StyleReceiver; import io.github.rosemoe.sora.lang.styling.CodeBlock; import io.github.rosemoe.sora.lang.styling.Span; import io.github.rosemoe.sora.lang.styling.Spans; import io.github.rosemoe.sora.lang.styling.Styles; import io.github.rosemoe.sora.text.CharPosition; import io.github.rosemoe.sora.text.Content; import io.github.rosemoe.sora.text.ContentLine; import io.github.rosemoe.sora.text.ContentReference; import io.github.rosemoe.sora.util.IntPair; import io.github.rosemoe.sora.widget.schemes.EditorColorScheme; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public abstract class BaseIncrementalAnalyzeManager<S, T> implements IncrementalAnalyzeManager<S, T> { private StyleReceiver receiver; private ContentReference ref; private Bundle extraArguments; private LooperThread thread; private volatile long runCount; private static int sThreadId = 0; private static final int MSG_BASE = 11451400; private static final int MSG_INIT = MSG_BASE + 1; private static final int MSG_MOD = MSG_BASE + 2; private static final int MSG_EXIT = MSG_BASE + 3; @Override public void setReceiver(StyleReceiver receiver) { this.receiver = receiver; } @Override public void reset(@NonNull ContentReference content, @NonNull Bundle extraArguments) { this.ref = content; this.extraArguments = extraArguments; rerun(); } @Override public void insert(CharPosition start, CharPosition end, CharSequence insertedText) { if (thread != null) { increaseRunCount(); thread.handler.sendMessage( thread.handler.obtainMessage( MSG_MOD, new TextModification( IntPair.pack(start.line, start.column), IntPair.pack(end.line, end.column), insertedText))); sendUpdate(thread.styles); } } @Override public void delete(CharPosition start, CharPosition end, CharSequence deletedText) { if (thread != null) { increaseRunCount(); thread.handler.sendMessage( thread.handler.obtainMessage( MSG_MOD, new TextModification( IntPair.pack(start.line, start.column), IntPair.pack(end.line, end.column), null))); sendUpdate(thread.styles); } } @Override public void rerun() { if (thread != null) { thread.callback = () -> { throw new CancelledException(); }; if (thread.isAlive()) { final Handler handler = thread.handler; if (handler != null) { handler.sendMessage(Message.obtain(thread.handler, MSG_EXIT)); } thread.abort = true; } } final Content text = ref.getReference().copyText(false); text.setUndoEnabled(false); thread = new LooperThread( () -> thread.handler.sendMessage(thread.handler.obtainMessage(MSG_INIT, text))); thread.setName("AsyncAnalyzer-" + nextThreadId()); increaseRunCount(); thread.start(); sendUpdate(null); } public abstract Result<S, T> tokenizeLine(CharSequence line, S state); @Override public Result<S, T> getState(int line) { final LooperThread thread = this.thread; if (thread == Thread.currentThread()) { return thread.states.get(line); } throw new SecurityException("Can not get state from non-analytical or abandoned thread"); } private synchronized void increaseRunCount() { runCount++; } private static synchronized int nextThreadId() { sThreadId++; return sThreadId; } @Override public void destroy() { if (thread != null) { thread.callback = () -> { throw new CancelledException(); }; if (thread.isAlive()) { thread.handler.sendMessage(Message.obtain(thread.handler, MSG_EXIT)); thread.abort = true; } } receiver = null; ref = null; extraArguments = null; thread = null; } private void sendUpdate(Styles styles) { final StyleReceiver r = receiver; if (r != null) { r.setStyles(this, styles); } } /** * Compute code blocks * * @param text The text. can be safely accessed. */ public abstract List<CodeBlock> computeBlocks(Content text, CodeBlockAnalyzeDelegate delegate); public Bundle getExtraArguments() { return extraArguments; } /** Helper class for analyzing code block */ public class CodeBlockAnalyzeDelegate { private final LooperThread thread; int suppressSwitch; CodeBlockAnalyzeDelegate(@NonNull LooperThread lp) { thread = lp; } public void setSuppressSwitch(int suppressSwitch) { this.suppressSwitch = suppressSwitch; } void reset() { suppressSwitch = Integer.MAX_VALUE; } public boolean isCancelled() { return thread.myRunCount != runCount; } public boolean isNotCancelled() { return thread.myRunCount == runCount; } } private class LooperThread extends Thread { volatile boolean abort; Looper looper; Handler handler; Content shadowed; long myRunCount; List<Result<S, T>> states = new ArrayList<>(); Styles styles; LockedSpans spans; Runnable callback; CodeBlockAnalyzeDelegate delegate = new CodeBlockAnalyzeDelegate(this); public LooperThread(Runnable callback) { this.callback = callback; } private void tryUpdate() { if (!abort) sendUpdate(styles); } private void initialize() { styles = new Styles(spans = new LockedSpans()); S state = getInitialState(); Spans.Modifier mdf = spans.modify(); for (int i = 0; i < shadowed.getLineCount(); i++) { ContentLine line = shadowed.getLine(i); Result<S, T> result = tokenizeLine(line, state); state = result.state; List<Span> spans = result.spans != null ? result.spans : generateSpansForLine(result); states.add(result.clearSpans()); mdf.addLineAt(i, spans); } styles.blocks = computeBlocks(shadowed, delegate); styles.setSuppressSwitch(delegate.suppressSwitch); tryUpdate(); } @Override public void run() { Looper.prepare(); looper = Looper.myLooper(); handler = new Handler(looper) { @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); try { myRunCount = runCount; delegate.reset(); switch (msg.what) { case MSG_INIT: shadowed = (Content) msg.obj; if (!abort) { initialize(); } break; case MSG_MOD: if (!abort) { TextModification mod = (TextModification) msg.obj; int startLine = IntPair.getFirst(mod.start); int endLine = IntPair.getFirst(mod.end); if (mod.changedText == null) { shadowed.delete( IntPair.getFirst(mod.start), IntPair.getSecond(mod.start), IntPair.getFirst(mod.end), IntPair.getSecond(mod.end)); S state = startLine == 0 ? getInitialState() : states.get(startLine - 1).state; // Remove states if (endLine >= startLine + 1) { states.subList(startLine + 1, endLine + 1).clear(); } Spans.Modifier mdf = spans.modify(); for (int i = startLine + 1; i <= endLine; i++) { mdf.deleteLineAt(startLine + 1); } int line = startLine; while (line < shadowed.getLineCount()) { Result<S, T> res = tokenizeLine(shadowed.getLine(line), state); mdf.setSpansOnLine( line, res.spans != null ? res.spans : generateSpansForLine(res)); Result<S, T> old = states.set(line, res.clearSpans()); if (stateEquals(old.state, res.state)) { break; } state = res.state; line++; } } else { shadowed.insert( IntPair.getFirst(mod.start), IntPair.getSecond(mod.start), mod.changedText); S state = startLine == 0 ? getInitialState() : states.get(startLine - 1).state; int line = startLine; Spans.Modifier spans = styles.spans.modify(); // Add Lines while (line <= endLine) { Result<S, T> res = tokenizeLine(shadowed.getLine(line), state); if (line == startLine) { spans.setSpansOnLine( line, res.spans != null ? res.spans : generateSpansForLine(res)); states.set(line, res.clearSpans()); } else { spans.addLineAt( line, res.spans != null ? res.spans : generateSpansForLine(res)); states.add(line, res.clearSpans()); } state = res.state; line++; } // line = end.line + 1, check whether the state equals while (line < shadowed.getLineCount()) { Result<S, T> res = tokenizeLine(shadowed.getLine(line), state); if (stateEquals(res.state, states.get(line).state)) { break; } else { spans.setSpansOnLine( line, res.spans != null ? res.spans : generateSpansForLine(res)); states.set(line, res.clearSpans()); } line++; } } } styles.blocks = computeBlocks(shadowed, delegate); styles.setSuppressSwitch(delegate.suppressSwitch); tryUpdate(); break; case MSG_EXIT: looper.quit(); break; } } catch (Exception e) { Log.w("AsyncAnalysis", "Thread " + Thread.currentThread().getName() + " failed", e); } } }; try { callback.run(); Looper.loop(); } catch (CancelledException e) { // ignored } } } private static class LockedSpans implements Spans { private final Lock lock; private final List<LockedSpans.Line> lines; public LockedSpans() { lines = new ArrayList<>(128); lock = new ReentrantLock(); } @Override public void adjustOnDelete(CharPosition start, CharPosition end) {} @Override public void adjustOnInsert(CharPosition start, CharPosition end) {} @Override public int getLineCount() { return lines.size(); } @Override public Reader read() { return new LockedSpans.ReaderImpl(); } @Override public Modifier modify() { return new LockedSpans.ModifierImpl(); } @Override public boolean supportsModify() { return true; } private static class Line { public Lock lock = new ReentrantLock(); public List<Span> spans; public Line() { this(null); } public Line(List<Span> s) { spans = s; } } private class ReaderImpl implements Spans.Reader { private LockedSpans.Line line; public void moveToLine(int line) { if (line < 0 || lines == null || line >= lines.size()) { if (this.line != null) { this.line.lock.unlock(); } this.line = null; } else { if (this.line != null) { this.line.lock.unlock(); } boolean locked = false; try { locked = lock.tryLock(1, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } if (locked) { try { Line obj = lines.get(line); if (obj.lock.tryLock()) { this.line = obj; } else { this.line = null; } } finally { lock.unlock(); } } else { this.line = null; } } } @Override public int getSpanCount() { return line == null || line.spans == null ? 1 : line.spans.size(); } @Override public Span getSpanAt(int index) { if (line == null || line.spans == null || index < 0 || index >= line.spans.size()) { return Span.obtain(0, EditorColorScheme.TEXT_NORMAL); } else { return line.spans.get(Math.min(index, line.spans.size() - 1)); } } @Override public List<Span> getSpansOnLine(int line) { ArrayList<Span> spans = new ArrayList<>(); boolean locked = false; try { locked = lock.tryLock(1, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } if (locked) { LockedSpans.Line obj = null; try { if (line < lines.size()) { obj = lines.get(line); } } finally { lock.unlock(); } if (obj != null && obj.lock.tryLock()) { try { return Collections.unmodifiableList(obj.spans); } finally { obj.lock.unlock(); } } else { spans.add(getSpanAt(0)); } } else { spans.add(getSpanAt(0)); } return spans; } } private class ModifierImpl implements Modifier { @Override public void setSpansOnLine(int line, List<Span> spans) { lock.lock(); try { while (lines.size() <= line) { ArrayList<Span> list = new ArrayList<>(); list.add(Span.obtain(0, EditorColorScheme.TEXT_NORMAL)); lines.add(new LockedSpans.Line(list)); } lines.get(line).spans = spans; } finally { lock.unlock(); } } @Override public void addLineAt(int line, List<Span> spans) { lock.lock(); try { if (lines != null) { lines.add(line, new LockedSpans.Line(spans)); } } finally { lock.unlock(); } } @Override public void deleteLineAt(int line) { lock.lock(); try { if (lines != null && line >= 0 && line < lines.size()) { Line obj = lines.get(line); if (obj != null) { obj.lock.lock(); try { lines.remove(line); } finally { obj.lock.unlock(); } } } } finally { lock.unlock(); } } } } private static class TextModification { private final long start; private final long end; /** null for deletion */ private final CharSequence changedText; TextModification(long start, long end, CharSequence text) { this.start = start; this.end = end; changedText = text; } } public static class Result<S_, T_> extends LineTokenizeResult<S_, T_> { public Result(@NonNull S_ state, @Nullable List<T_> tokens) { super(state, tokens); } public Result(@NonNull S_ state, @Nullable List<T_> tokens, @Nullable List<Span> spans) { super(state, tokens, spans); } @Override public Result<S_, T_> clearSpans() { super.clearSpans(); return this; } } private static class CancelledException extends RuntimeException {} }
17,182
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
EmptyTextMateLanguage.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/app/src/main/java/com/tyron/code/language/textmate/EmptyTextMateLanguage.java
package com.tyron.code.language.textmate; import io.github.rosemoe.sora.lang.EmptyLanguage; public class EmptyTextMateLanguage extends EmptyLanguage {}
154
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z