From 0531748d76f67ababf1cfad74019839c292b9f58 Mon Sep 17 00:00:00 2001 From: plamen5kov Date: Fri, 11 Aug 2017 09:08:53 +0300 Subject: [PATCH 1/2] copy java files to project template on build and clean them afterwards --- .../src/debug/java/com/tns/ErrorReport.java | 417 ------------------ .../java/com/tns/ErrorReportActivity.java | 44 -- .../java/com/tns/NativeScriptSyncService.java | 332 -------------- .../src/main/assets/internal/livesync.js | 3 - .../src/main/assets/internal/ts_helpers.js | 127 ------ .../java/com/tns/AndroidJsV8Inspector.java | 324 -------------- .../java/com/tns/DefaultExtractPolicy.java | 125 ------ .../src/main/java/com/tns/LogcatLogger.java | 41 -- .../java/com/tns/NativeScriptApplication.java | 29 -- .../NativeScriptUncaughtExceptionHandler.java | 90 ---- .../src/main/java/com/tns/RuntimeHelper.java | 237 ---------- .../src/main/java/com/tns/Util.java | 100 ----- .../com/tns/internal/AppBuilderCallback.java | 21 - .../main/java/com/tns/internal/Plugin.java | 5 - build.gradle | 47 +- .../src/main/assets/internal/ts_helpers.js | 5 +- .../java/com/tns/NativeScriptApplication.java | 1 - .../NativeScriptUncaughtExceptionHandler.java | 46 +- .../src/main/res/layout/error_activity.xml | 3 +- .../app/src/main/res/layout/exception_tab.xml | 1 - .../app/src/main/res/layout/logcat_tab.xml | 3 +- 21 files changed, 92 insertions(+), 1909 deletions(-) delete mode 100644 build-artifacts/project-template-gradle/src/debug/java/com/tns/ErrorReport.java delete mode 100644 build-artifacts/project-template-gradle/src/debug/java/com/tns/ErrorReportActivity.java delete mode 100644 build-artifacts/project-template-gradle/src/debug/java/com/tns/NativeScriptSyncService.java delete mode 100644 build-artifacts/project-template-gradle/src/main/assets/internal/livesync.js delete mode 100644 build-artifacts/project-template-gradle/src/main/assets/internal/ts_helpers.js delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/AndroidJsV8Inspector.java delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/DefaultExtractPolicy.java delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/LogcatLogger.java delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/NativeScriptApplication.java delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/RuntimeHelper.java delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/Util.java delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/internal/AppBuilderCallback.java delete mode 100644 build-artifacts/project-template-gradle/src/main/java/com/tns/internal/Plugin.java diff --git a/build-artifacts/project-template-gradle/src/debug/java/com/tns/ErrorReport.java b/build-artifacts/project-template-gradle/src/debug/java/com/tns/ErrorReport.java deleted file mode 100644 index d319841b2..000000000 --- a/build-artifacts/project-template-gradle/src/debug/java/com/tns/ErrorReport.java +++ /dev/null @@ -1,417 +0,0 @@ -package com.tns; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Method; -import java.text.SimpleDateFormat; -import java.util.Date; - -import android.Manifest; -import android.app.Activity; -import android.app.PendingIntent; -import android.app.PendingIntent.CanceledException; -import android.content.ClipData; -import android.content.ClipboardManager; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.graphics.Color; -import android.os.Build; -import android.os.Bundle; -import android.os.Environment; -import android.support.design.widget.TabLayout; -import android.support.v4.app.ActivityCompat; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentStatePagerAdapter; -import android.support.v4.view.ViewPager; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.text.method.ScrollingMovementMethod; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.TextView; -import android.widget.Toast; - - -class ErrorReport implements TabLayout.OnTabSelectedListener { - public static final String ERROR_FILE_NAME = "hasError"; - private static AppCompatActivity activity; - - private TabLayout tabLayout; - private ViewPager viewPager; - private Context context; - - private static String exceptionMsg; - private static String logcatMsg; - - private static boolean checkingForPermissions = false; - - private final static String EXTRA_NATIVESCRIPT_ERROR_REPORT = "NativeScriptErrorMessage"; - private final static String EXTRA_ERROR_REPORT_MSG = "msg"; - private final static String EXTRA_PID = "pID"; - private final static int EXTRA_ERROR_REPORT_VALUE = 1; - - private static final int REQUEST_EXTERNAL_STORAGE = 1; - private static String[] PERMISSIONS_STORAGE = { - Manifest.permission.READ_EXTERNAL_STORAGE, - Manifest.permission.WRITE_EXTERNAL_STORAGE - }; - - // Will prevent error activity from killing process if permission request dialog pops up - public static boolean isCheckingForPermissions() { - return checkingForPermissions; - } - - public static void resetCheckingForPermissions() { - checkingForPermissions = false; - } - - // The following will not compile if uncommented with compileSdk lower than 23 - public static void verifyStoragePermissions(Activity activity) { - // Check if we have write permission - final int version = Build.VERSION.SDK_INT; - if (version >= 23) { - try { - // Necessary to work around compile errors with compileSdk 22 and lower - Method checkSelfPermissionMethod; - try { - checkSelfPermissionMethod = ActivityCompat.class.getMethod("checkSelfPermission", Context.class, String.class); - } catch (NoSuchMethodException e) { - // method wasn't found, so there is no need to handle permissions explicitly - e.printStackTrace(); - return; - } - - int permission = (int) checkSelfPermissionMethod.invoke(null, activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); - - if (permission != PackageManager.PERMISSION_GRANTED) { - // We don't have permission so prompt the user - Method requestPermissionsMethod = ActivityCompat.class.getMethod("requestPermissions", Activity.class, PERMISSIONS_STORAGE.getClass(), int.class); - - checkingForPermissions = true; - - requestPermissionsMethod.invoke(null, activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); - } - } catch (Exception e) { - Toast.makeText(activity, "Couldn't resolve permissions", Toast.LENGTH_LONG).show(); - e.printStackTrace(); - return; - } - } - } - - public ErrorReport(AppCompatActivity activity) { - ErrorReport.activity = activity; - this.context = activity.getApplicationContext(); - } - - static boolean startActivity(final Context context, String errorMessage) { - final Intent intent = getIntent(context); - if (intent == null) { - return false; // (if in release mode) don't do anything - } - - intent.putExtra(EXTRA_ERROR_REPORT_MSG, errorMessage); - - String PID = Integer.toString(android.os.Process.myPid()); - intent.putExtra(EXTRA_PID, PID); - - createErrorFile(context); - - try { - startPendingErrorActivity(context, intent); - } catch (CanceledException e) { - Log.d("ErrorReport", "Couldn't send pending intent! Exception: " + e.getMessage()); - } - - killProcess(context); - - return true; - } - - static void killProcess(Context context) { - // finish current activity and all below it first - if (context instanceof Activity) { - ((Activity) context).finishAffinity(); - } - - // kill process - android.os.Process.killProcess(android.os.Process.myPid()); - } - - static void startPendingErrorActivity(Context context, Intent intent) throws CanceledException { - PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); - - pendingIntent.send(context, 0, intent); - } - - static String getErrorMessage(Throwable ex) { - String content; - PrintStream ps = null; - - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ps = new PrintStream(baos); - ex.printStackTrace(ps); - - try { - content = baos.toString("US-ASCII"); - } catch (UnsupportedEncodingException e) { - content = e.getMessage(); - } - } finally { - if (ps != null) { - ps.close(); - } - } - - return content; - } - - /* - * Gets the process Id of the running app and filters all - * output that doesn't belong to that process - * */ - public static String getLogcat(String pId) { - String content; - - try { - String logcatCommand = "logcat -d"; - Process process = java.lang.Runtime.getRuntime().exec(logcatCommand); - - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(process.getInputStream())); - - StringBuilder log = new StringBuilder(); - String line = ""; - String lineSeparator = System.getProperty("line.separator"); - while ((line = bufferedReader.readLine()) != null) { - if (line.contains(pId)) { - log.append(line); - log.append(lineSeparator); - } - } - - content = log.toString(); - } catch (IOException e) { - content = "Failed to read logcat"; - Log.e("TNS.Android", content); - } - - return content; - } - - static Intent getIntent(Context context) { - Class errorActivityClass; - - if (Util.isDebuggableApp(context)) { - errorActivityClass = ErrorReportActivity.class; - } else { - return null; - } - - Intent intent = new Intent(context, errorActivityClass); - - intent.putExtra(EXTRA_NATIVESCRIPT_ERROR_REPORT, EXTRA_ERROR_REPORT_VALUE); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); - - return intent; - } - - static boolean hasIntent(Intent intent) { - int value = intent.getIntExtra(EXTRA_NATIVESCRIPT_ERROR_REPORT, 0); - - return value == EXTRA_ERROR_REPORT_VALUE; - } - - void buildUI() { - Intent intent = activity.getIntent(); - - exceptionMsg = intent.getStringExtra(EXTRA_ERROR_REPORT_MSG); - - String processId = intent.getStringExtra(EXTRA_PID); - logcatMsg = getLogcat(processId); - - int errActivityId = this.context.getResources().getIdentifier("error_activity", "layout", this.context.getPackageName()); - - activity.setContentView(errActivityId); - - int toolBarId = this.context.getResources().getIdentifier("toolbar", "id", this.context.getPackageName()); - - Toolbar toolbar = (Toolbar) activity.findViewById(toolBarId); - activity.setSupportActionBar(toolbar); - - final int tabLayoutId = this.context.getResources().getIdentifier("tabLayout", "id", this.context.getPackageName()); - - tabLayout = (TabLayout) activity.findViewById(tabLayoutId); - tabLayout.addTab(tabLayout.newTab().setText("Exception")); - tabLayout.addTab(tabLayout.newTab().setText("Logcat")); - tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); - int pagerId = this.context.getResources().getIdentifier("pager", "id", this.context.getPackageName()); - - viewPager = (ViewPager) activity.findViewById(pagerId); - - Pager adapter = new Pager(activity.getSupportFragmentManager(), tabLayout.getTabCount()); - - viewPager.setAdapter(adapter); - viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { - @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { - - } - - @Override - public void onPageSelected(int position) { - tabLayout.getTabAt(position).select(); - viewPager.setCurrentItem(position); - } - - @Override - public void onPageScrollStateChanged(int state) { - - } - }); - - tabLayout.setOnTabSelectedListener(this); - } - - private static void createErrorFile(final Context context) { - try { - File errFile = new File(context.getFilesDir(), ERROR_FILE_NAME); - errFile.createNewFile(); - } catch (IOException e) { - Log.d("ErrorReport", e.getMessage()); - } - } - - @Override - public void onTabSelected(TabLayout.Tab tab) { - viewPager.setCurrentItem(tab.getPosition()); - } - - @Override - public void onTabUnselected(TabLayout.Tab tab) { - - } - - @Override - public void onTabReselected(TabLayout.Tab tab) { - viewPager.setCurrentItem(tab.getPosition()); - } - - private class Pager extends FragmentStatePagerAdapter { - - int tabCount; - - public Pager(FragmentManager fm, int tabCount) { - super(fm); - this.tabCount = tabCount; - } - - @Override - public Fragment getItem(int position) { - switch (position) { - case 0: - return new ExceptionTab(); - case 1: - return new LogcatTab(); - default: - return null; - } - } - - @Override - public int getCount() { - return tabCount; - } - } - - public static class ExceptionTab extends Fragment { - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - int exceptionTabId = container.getContext().getResources().getIdentifier("exception_tab", "layout", container.getContext().getPackageName()); - View view = inflater.inflate(exceptionTabId, container, false); - - int txtViewId = container.getContext().getResources().getIdentifier("txtErrorMsg", "id", container.getContext().getPackageName()); - TextView txtErrorMsg = (TextView) view.findViewById(txtViewId); - txtErrorMsg.setText(exceptionMsg); - txtErrorMsg.setMovementMethod(new ScrollingMovementMethod()); - - int btnCopyExceptionId = container.getContext().getResources().getIdentifier("btnCopyException", "id", container.getContext().getPackageName()); - Button copyToClipboard = (Button) view.findViewById(btnCopyExceptionId); - copyToClipboard.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText("nsError", exceptionMsg); - clipboard.setPrimaryClip(clip); - } - }); - - return view; - } - } - - public static class LogcatTab extends Fragment { - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - int logcatTabId = container.getContext().getResources().getIdentifier("logcat_tab", "layout", container.getContext().getPackageName()); - View view = inflater.inflate(logcatTabId, container, false); - - int textViewId = container.getContext().getResources().getIdentifier("logcatMsg", "id", container.getContext().getPackageName()); - TextView txtlogcatMsg = (TextView) view.findViewById(textViewId); - txtlogcatMsg.setText(logcatMsg); - - txtlogcatMsg.setMovementMethod(new ScrollingMovementMethod()); - - final String logName = "Log-" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()); - - int btnCopyLogcatId = container.getContext().getResources().getIdentifier("btnCopyLogcat", "id", container.getContext().getPackageName()); - Button copyToClipboard = (Button) view.findViewById(btnCopyLogcatId); - copyToClipboard.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - verifyStoragePermissions(activity); - - if (!isCheckingForPermissions()) { - try { - File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/logcat-reports/"); - dir.mkdirs(); - - File logcatReportFile = new File(dir, logName); - FileOutputStream stream = new FileOutputStream(logcatReportFile); - OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8"); - writer.write(logcatMsg); - writer.close(); - - String logPath = dir.getPath() + "/" + logName; - - ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); - ClipData clip = ClipData.newPlainText("logPath", logPath); - clipboard.setPrimaryClip(clip); - - Toast.makeText(activity, "Path copied to clipboard: " + logPath, Toast.LENGTH_LONG).show(); - } catch (Exception e) { - String err = "Could not write logcat report to sdcard. Make sure you have allowed access to external storage!"; - Toast.makeText(activity, err, Toast.LENGTH_LONG).show(); - e.printStackTrace(); - } - } - } - }); - - return view; - } - } -} \ No newline at end of file diff --git a/build-artifacts/project-template-gradle/src/debug/java/com/tns/ErrorReportActivity.java b/build-artifacts/project-template-gradle/src/debug/java/com/tns/ErrorReportActivity.java deleted file mode 100644 index 5a55354a4..000000000 --- a/build-artifacts/project-template-gradle/src/debug/java/com/tns/ErrorReportActivity.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.tns; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.v7.app.AppCompatActivity; -import android.widget.Toast; - -import java.lang.reflect.Method; - -import static com.tns.ErrorReport.isCheckingForPermissions; -import static com.tns.ErrorReport.resetCheckingForPermissions; - -public class ErrorReportActivity extends AppCompatActivity { - public void onCreate(Bundle savedInstanceState) { - setTheme(android.support.v7.appcompat.R.style.Theme_AppCompat_NoActionBar); - - super.onCreate(savedInstanceState); - - new ErrorReport(this).buildUI(); - } - - @Override - protected void onUserLeaveHint() { - super.onUserLeaveHint(); - - if (!isCheckingForPermissions()) { - ErrorReport.killProcess(this); - } - } - - // @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - try { - Method onRequestPermissionsResultMethod = AppCompatActivity.class.getMethod("onRequestPermissionsResult", int.class, permissions.getClass(), grantResults.getClass()); - onRequestPermissionsResultMethod.invoke(new AppCompatActivity() /* never do this */, requestCode, permissions, grantResults); - - resetCheckingForPermissions(); - } catch (Exception e) { - e.printStackTrace(); - Toast.makeText(this, "Couldn't resolve permissions", Toast.LENGTH_LONG).show(); - resetCheckingForPermissions(); - } - } -} diff --git a/build-artifacts/project-template-gradle/src/debug/java/com/tns/NativeScriptSyncService.java b/build-artifacts/project-template-gradle/src/debug/java/com/tns/NativeScriptSyncService.java deleted file mode 100644 index a443b358e..000000000 --- a/build-artifacts/project-template-gradle/src/debug/java/com/tns/NativeScriptSyncService.java +++ /dev/null @@ -1,332 +0,0 @@ -package com.tns; - -import java.io.Closeable; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager.NameNotFoundException; -import android.net.LocalServerSocket; -import android.net.LocalSocket; -import android.util.Log; - -public class NativeScriptSyncService { - private static String SYNC_ROOT_SOURCE_DIR = "/data/local/tmp/"; - private static final String SYNC_SOURCE_DIR = "/sync/"; - private static final String FULL_SYNC_SOURCE_DIR = "/fullsync/"; - private static final String REMOVED_SYNC_SOURCE_DIR = "/removedsync/"; - - private final Runtime runtime; - private static Logger logger; - private final Context context; - - private final String syncPath; - private final String fullSyncPath; - private final String removedSyncPath; - private final File fullSyncDir; - private final File syncDir; - private final File removedSyncDir; - - private LocalServerSocketThread localServerThread; - private Thread localServerJavaThread; - - public NativeScriptSyncService(Runtime runtime, Logger logger, Context context) { - this.runtime = runtime; - this.logger = logger; - this.context = context; - - syncPath = SYNC_ROOT_SOURCE_DIR + context.getPackageName() + SYNC_SOURCE_DIR; - fullSyncPath = SYNC_ROOT_SOURCE_DIR + context.getPackageName() + FULL_SYNC_SOURCE_DIR; - removedSyncPath = SYNC_ROOT_SOURCE_DIR + context.getPackageName() + REMOVED_SYNC_SOURCE_DIR; - fullSyncDir = new File(fullSyncPath); - syncDir = new File(syncPath); - removedSyncDir = new File(removedSyncPath); - } - - public void sync() { - if (logger != null && logger.isEnabled()) { - logger.write("Sync is enabled:"); - logger.write("Sync path : " + syncPath); - logger.write("Full sync path : " + fullSyncPath); - logger.write("Removed files sync path: " + removedSyncPath); - } - - if (fullSyncDir.exists()) { - executeFullSync(context, fullSyncDir); - return; - } - - if (syncDir.exists()) { - executePartialSync(context, syncDir); - } - - if (removedSyncDir.exists()) { - executeRemovedSync(context, removedSyncDir); - } - } - - private class LocalServerSocketThread implements Runnable { - private volatile boolean running; - private final String name; - - private ListenerWorker commThread; - private LocalServerSocket serverSocket; - - public LocalServerSocketThread(String name) { - this.name = name; - this.running = false; - } - - public void stop() { - this.running = false; - try { - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void run() { - running = true; - try { - serverSocket = new LocalServerSocket(this.name); - while (running) { - LocalSocket socket = serverSocket.accept(); - commThread = new ListenerWorker(socket); - new Thread(commThread).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - private class ListenerWorker implements Runnable { - private final DataInputStream input; - private Closeable socket; - private OutputStream output; - - public ListenerWorker(LocalSocket socket) throws IOException { - this.socket = socket; - input = new DataInputStream(socket.getInputStream()); - output = socket.getOutputStream(); - } - - public void run() { - try { - int length = input.readInt(); - input.readFully(new byte[length]); // ignore the payload - executePartialSync(context, syncDir); - executeRemovedSync(context, removedSyncDir); - - runtime.runScript(new File(NativeScriptSyncService.this.context.getFilesDir(), "internal/livesync.js")); - try { - output.write(1); - } catch (IOException e) { - e.printStackTrace(); - } - socket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void startServer() { - localServerThread = new LocalServerSocketThread(context.getPackageName() + "-livesync"); - localServerJavaThread = new Thread(localServerThread); - localServerJavaThread.start(); - } - - public static boolean isSyncEnabled(Context context) { - int flags; - boolean shouldExecuteSync = false; - try { - flags = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.flags; - shouldExecuteSync = ((flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); - } catch (NameNotFoundException e) { - e.printStackTrace(); - return false; - } - - return shouldExecuteSync; - } - - final FileFilter deletingFilesFilter = new FileFilter() { - @Override - public boolean accept(File pathname) { - if (pathname.isDirectory()) { - return true; - } - - boolean success = pathname.delete(); - if (!success) { - logger.write("Syncing: file not deleted: " + pathname.getAbsolutePath().toString()); - } - return false; - } - }; - - private void deleteDir(File directory) { - File[] subDirectories = directory.listFiles(deletingFilesFilter); - if (subDirectories != null) { - for (int i = 0; i < subDirectories.length; i++) { - File subDir = subDirectories[i]; - deleteDir(subDir); - } - } - - boolean success = directory.delete(); - if (!success && directory.exists()) { - logger.write("Syncing: directory not deleted: " + directory.getAbsolutePath().toString()); - } - } - - private void moveFiles(File sourceDir, String sourceRootAbsolutePath, String targetRootAbsolutePath) { - File[] files = sourceDir.listFiles(); - - if (files != null) { - if (logger.isEnabled()) { - logger.write("Syncing total number of fiiles: " + files.length); - } - - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (file.isFile()) { - if (logger.isEnabled()) { - logger.write("Syncing: " + file.getAbsolutePath().toString()); - } - - String targetFilePath = file.getAbsolutePath().replace(sourceRootAbsolutePath, targetRootAbsolutePath); - File targetFileDir = new File(targetFilePath); - - File targetParent = targetFileDir.getParentFile(); - if (targetParent != null) { - targetParent.mkdirs(); - } - - boolean success = copyFile(file.getAbsolutePath(), targetFilePath); - if (!success) { - logger.write("Sync failed: " + file.getAbsolutePath().toString()); - } - } else { - moveFiles(file, sourceRootAbsolutePath, targetRootAbsolutePath); - } - } - } else { - if (logger.isEnabled()) { - logger.write("Can't move files. Source is empty."); - } - } - } - - // this removes only the app directory from the device to preserve - // any existing files in /files directory on the device - private void executeFullSync(Context context, final File sourceDir) { - String appPath = context.getFilesDir().getAbsolutePath() + "/app"; - final File appDir = new File(appPath); - - if (appDir.exists()) { - deleteDir(appDir); - moveFiles(sourceDir, sourceDir.getAbsolutePath(), appDir.getAbsolutePath()); - } - } - - private void executePartialSync(Context context, File sourceDir) { - String appPath = context.getFilesDir().getAbsolutePath() + "/app"; - final File appDir = new File(appPath); - - if (!appDir.exists()) { - Log.e("TNS", "Application dir does not exists. Partial Sync failed. appDir: " + appPath); - return; - } - - if (logger.isEnabled()) { - logger.write("Syncing sourceDir " + sourceDir.getAbsolutePath() + " with " + appDir.getAbsolutePath()); - } - - moveFiles(sourceDir, sourceDir.getAbsolutePath(), appDir.getAbsolutePath()); - } - - private void deleteRemovedFiles(File sourceDir, String sourceRootAbsolutePath, String targetRootAbsolutePath) { - if (!sourceDir.exists()) { - if (logger.isEnabled()) { - logger.write("Directory does not exist: " + sourceDir.getAbsolutePath()); - } - } - - File[] files = sourceDir.listFiles(); - - if (files != null) { - for (int i = 0; i < files.length; i++) { - File file = files[i]; - String targetFilePath = file.getAbsolutePath().replace(sourceRootAbsolutePath, targetRootAbsolutePath); - File targetFile = new File(targetFilePath); - if (file.isFile()) { - if (logger.isEnabled()) { - logger.write("Syncing removed file: " + file.getAbsolutePath().toString()); - } - - targetFile.delete(); - } else { - deleteRemovedFiles(file, sourceRootAbsolutePath, targetRootAbsolutePath); - - // this is done so empty folders, if any, are deleted after we're don deleting files. - if (targetFile.listFiles().length == 0) { - targetFile.delete(); - } - } - } - } - } - - private void executeRemovedSync(final Context context, final File sourceDir) { - String appPath = context.getFilesDir().getAbsolutePath() + "/app"; - deleteRemovedFiles(sourceDir, sourceDir.getAbsolutePath(), appPath); - } - - private boolean copyFile(String sourceFile, String destinationFile) { - FileInputStream fis = null; - FileOutputStream fos = null; - - try { - fis = new FileInputStream(sourceFile); - fos = new FileOutputStream(destinationFile, false); - - byte[] buffer = new byte[4096]; - int read = 0; - - while ((read = fis.read(buffer)) != -1) { - fos.write(buffer, 0, read); - } - } catch (FileNotFoundException e) { - logger.write("Error copying file " + sourceFile); - e.printStackTrace(); - return false; - } catch (IOException e) { - logger.write("Error copying file " + sourceFile); - e.printStackTrace(); - return false; - } finally { - try { - if (fis != null) { - fis.close(); - } - if (fos != null) { - fos.close(); - } - } catch (IOException e) { - } - } - - return true; - } -} diff --git a/build-artifacts/project-template-gradle/src/main/assets/internal/livesync.js b/build-artifacts/project-template-gradle/src/main/assets/internal/livesync.js deleted file mode 100644 index 5f10e08b7..000000000 --- a/build-artifacts/project-template-gradle/src/main/assets/internal/livesync.js +++ /dev/null @@ -1,3 +0,0 @@ -if (global.__onLiveSync) { - global.__onLiveSync(); -} \ No newline at end of file diff --git a/build-artifacts/project-template-gradle/src/main/assets/internal/ts_helpers.js b/build-artifacts/project-template-gradle/src/main/assets/internal/ts_helpers.js deleted file mode 100644 index aba1778fd..000000000 --- a/build-artifacts/project-template-gradle/src/main/assets/internal/ts_helpers.js +++ /dev/null @@ -1,127 +0,0 @@ -(function() { - var __extends_ts = function (d, b) { - if (!b.extend) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - } - - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); - }; - - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length; - var r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - - if (typeof global.Reflect === "object" && typeof global.Reflect.decorate === "function") { - r = global.Reflect.decorate(decorators, target, key, desc); - } - else { - for (var i = decorators.length - 1; i >= 0; i--) { - if (d = decorators[i]) { - r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - } - } - } - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - var __native = function(thiz) { - var result = thiz.__proto__; - - for (var prop in thiz) - { - if (thiz.hasOwnProperty(prop)) - { - thiz.__proto__[prop] = thiz[prop]; - delete thiz[prop]; - } - } - - thiz.constructor = undefined; - thiz.__proto__ = undefined; - Object.freeze(thiz); - Object.preventExtensions(thiz) - return result; - }; - - var __extends = function(Child, Parent) { - - if (Parent.extend) { - if (Parent.__isPrototypeImplementationObject) { - throw new Error("Can not extend an already extended native object."); - } - - function extend(child, parent) { - __log("TS extend called"); - if (!child.__extended) { - child.__extended = parent.extend(child.name, child.prototype); - } - - return child.__extended; - }; - - Parent.__activityExtend = function(parent, name, implementationObject) { - __log("__activityExtend called"); - return parent.extend(name, implementationObject); - }; - - Parent.call = function(thiz) { - var Extended = extend(thiz.__proto__.__child, thiz.__proto__.__parent); - if (arguments.length > 1) - { - thiz.__proto__ = new (Function.prototype.bind.apply(Extended, [null].concat(Array.prototype.slice.call(arguments, 1)))); - } - else - { - thiz.__proto__ = new Extended(); - } - }; - - Parent.apply = function(thiz, args) { - var Extended = extend(thiz.__proto__.__child, thiz.__proto__.__parent); - if (args && args.length > 0) - { - thiz.__proto__ = new (Function.prototype.bind.apply(Extended, [null].concat(args))); - } - else - { - thiz.__proto__ = new Extended(); - } - }; - } - - __extends_ts(Child, Parent); - - - if (Parent.extend) { - Child.__isPrototypeImplementationObject = true; - Child.__proto__ = Parent; - Child.prototype.__parent = Parent; - Child.prototype.__child = Child; - } - } - - function JavaProxy(className) { - return function (target) { - var extended = target.extend(className, target.prototype) - extended.name = className; - return extended; - }; - } - - function Interfaces(interfacesArr) { - return function (target) { - if(interfacesArr instanceof Array) { - // attach interfaces: [] to the object - target.prototype.interfaces = interfacesArr; - } - } - } - - global.__native = __native; - global.__extends = __extends; - global.__decorate = __decorate; - global.JavaProxy = JavaProxy; - global.Interfaces = Interfaces; -})() \ No newline at end of file diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/AndroidJsV8Inspector.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/AndroidJsV8Inspector.java deleted file mode 100644 index a6b6ff916..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/AndroidJsV8Inspector.java +++ /dev/null @@ -1,324 +0,0 @@ -package com.tns; - -import android.os.Handler; -import android.util.Log; -import android.util.Pair; -import android.webkit.MimeTypeMap; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicBoolean; - -import fi.iki.elonen.NanoHTTPD; -import fi.iki.elonen.NanoWSD; - -class AndroidJsV8Inspector { - private static boolean DEBUG_LOG_ENABLED = false; - - private JsV8InspectorServer server; - private static String ApplicationDir; - private String packageName; - - protected native final void init(); - - protected native final void connect(Object connection); - - private native void scheduleBreak(); - - protected static native void disconnect(); - - protected native final void dispatchMessage(String message); - - private Handler mainHandler; - - private final Object debugBrkLock; - - private static AtomicBoolean ReadyToProcessMessages = new AtomicBoolean(false); - - private LinkedBlockingQueue inspectorMessages = new LinkedBlockingQueue(); - private LinkedBlockingQueue pendingInspectorMessages = new LinkedBlockingQueue(); - - AndroidJsV8Inspector(String filesDir, String packageName) { - ApplicationDir = filesDir; - this.packageName = packageName; - this.debugBrkLock = new Object(); - } - - public void start() throws IOException { - if (this.server == null) { - Runtime currentRuntime = Runtime.getCurrentRuntime(); - - mainHandler = currentRuntime.getHandler(); - - this.server = new JsV8InspectorServer(this.packageName + "-inspectorServer"); - this.server.start(-1); - - if (DEBUG_LOG_ENABLED) { - Log.d("V8Inspector", "start debugger ThreadId:" + Thread.currentThread().getId()); - } - - init(); - } - } - - @RuntimeCallable - private static void sendToDevToolsConsole(Object connection, String message, String level) { - try { - JSONObject consoleMessage = new JSONObject(); - - JSONObject params = new JSONObject(); - params.put("type", level); - params.put("executionContextId", 0); - params.put("timestamp", 0.000000000000000); - - JSONArray args = new JSONArray(); - args.put(message); - params.put("args", args); - - consoleMessage.put("method", "Runtime.consoleAPICalled"); - consoleMessage.put("params", params); - - String sendingText = consoleMessage.toString(); - AndroidJsV8Inspector.send(connection, sendingText); - - } catch (JSONException | IOException e) { - e.printStackTrace(); - } - } - - @RuntimeCallable - private static void send(Object connection, String payload) throws IOException { - ((JsV8InspectorWebSocket) connection).send(payload); - } - - @RuntimeCallable - private static String getInspectorMessage(Object connection) { - return ((JsV8InspectorWebSocket) connection).getInspectorMessage(); - } - - @RuntimeCallable - public static Pair[] getPageResources() { - // necessary to align the data dir returned by context (emulator) and that used by the v8 inspector - if (ApplicationDir.startsWith("/data/user/0/")) { - ApplicationDir = ApplicationDir.replaceFirst("/data/user/0/", "/data/data/"); - } - - String dataDir = ApplicationDir; - File rootFilesDir = new File(dataDir, "app"); - - - List> resources = traverseResources(rootFilesDir); - - return resources.toArray((Pair[]) Array.newInstance(resources.get(0).getClass(), resources.size())); - } - - private static List> traverseResources(File dir) { - List> resources = new ArrayList<>(); - - Queue directories = new LinkedList<>(); - directories.add(dir); - - while (!directories.isEmpty()) { - File currentDir = directories.poll(); - - File[] files = currentDir.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - directories.add(file); - } else { - resources.add(new Pair<>("file://" + file.getAbsolutePath(), getMimeType(file.getAbsolutePath()))); - } - } - } - - return resources; - } - - private static String getMimeType(String url) { - String type = null; - String extension = MimeTypeMap.getFileExtensionFromUrl(url); - if (!extension.isEmpty()) { - type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - - // getMimeType may sometime return incorrect results in the context of NativeScript - // e.g. `.ts` returns video/MP2TS - switch (extension) { - case "js": - type = "text/javascript"; - break; - case "json": - type = "application/json"; - break; - case "css": - type = "text/css"; - break; - case "ts": - type = "text/typescript"; - break; - // handle shared libraries so they are marked properly and don't appear in the sources tab - case "so": - type = "application/binary"; - break; - } - } - - return type; - } - - // pause the main thread for 30 seconds (30 * 1000 ms) - // allowing the devtools frontend to establish connection with the inspector - protected void waitForDebugger(boolean shouldBreak) { - if (shouldBreak) { - synchronized (this.debugBrkLock) { - try { - this.debugBrkLock.wait(1000 * 30); - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - AndroidJsV8Inspector.ReadyToProcessMessages.set(true); - this.processDebugBreak(); - } - } - } else { - AndroidJsV8Inspector.ReadyToProcessMessages.set(true); - } - } - - // process all messages coming from the frontend necessary to initialize the inspector backend - // schedule a debug line break at first convenience - private void processDebugBreak() { - processDebugBreakMessages(); - scheduleBreak(); - } - - private void processDebugBreakMessages() { - while (!pendingInspectorMessages.isEmpty()) { - String inspectorMessage = pendingInspectorMessages.poll(); - dispatchMessage(inspectorMessage); - } - } - - private class JsV8InspectorServer extends NanoWSD { - JsV8InspectorServer(String name) { - super(name); - } - - @Override - protected Response serveHttp(IHTTPSession session) { - if (DEBUG_LOG_ENABLED) { - Log.d("{N}.v8-inspector", "http request for " + session.getUri()); - } - return super.serveHttp(session); - } - - @Override - protected WebSocket openWebSocket(IHTTPSession handshake) { - return new JsV8InspectorWebSocket(handshake); - } - } - - private class JsV8InspectorWebSocket extends NanoWSD.WebSocket { - JsV8InspectorWebSocket(NanoHTTPD.IHTTPSession handshakeRequest) { - super(handshakeRequest); - } - - @Override - protected void onOpen() { - if (DEBUG_LOG_ENABLED) { - Log.d("V8Inspector", "onOpen: ThreadID: " + Thread.currentThread().getId()); - } - - connect(JsV8InspectorWebSocket.this); - } - - @Override - protected void onClose(NanoWSD.WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) { - if (DEBUG_LOG_ENABLED) { - Log.d("V8Inspector", "onClose"); - } - - mainHandler.post(new Runnable() { - @Override - public void run() { - if (DEBUG_LOG_ENABLED) { - Log.d("V8Inspector", "Disconnecting"); - } - disconnect(); - } - }); - } - - @Override - protected void onMessage(final NanoWSD.WebSocketFrame message) { - if (DEBUG_LOG_ENABLED) { - Log.d("V8Inspector", "To dbg backend: " + message.getTextPayload() + " ThreadId:" + Thread.currentThread().getId()); - } - - inspectorMessages.offer(message.getTextPayload()); - - if (!AndroidJsV8Inspector.ReadyToProcessMessages.get()) { - String nextMessage = inspectorMessages.poll(); - while (nextMessage != null) { - pendingInspectorMessages.offer(nextMessage); - nextMessage = inspectorMessages.poll(); - } - - if (message.getTextPayload().contains("Debugger.enable")) { - synchronized (debugBrkLock) { - debugBrkLock.notify(); - } - } - } else { - mainHandler.postAtFrontOfQueue(new Runnable() { - @Override - public void run() { - String nextMessage = inspectorMessages.poll(); - while (nextMessage != null) { - dispatchMessage(nextMessage); - nextMessage = inspectorMessages.poll(); - } - } - }); - } - } - - @Override - public void send(String payload) throws IOException { - if (DEBUG_LOG_ENABLED) { - Log.d("V8Inspector", "To dbg client: " + payload); - } - - super.send(payload); - } - - public String getInspectorMessage() { - try { - return inspectorMessages.take(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - return null; - } - - @Override - protected void onPong(NanoWSD.WebSocketFrame pong) { - } - - @Override - protected void onException(IOException exception) { - exception.printStackTrace(); - disconnect(); - } - } -} diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/DefaultExtractPolicy.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/DefaultExtractPolicy.java deleted file mode 100644 index d1ecf15c0..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/DefaultExtractPolicy.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.tns; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; - -import android.content.Context; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; - -import com.tns.Logger; -import com.tns.ExtractPolicy; -import com.tns.FileExtractor; - -public class DefaultExtractPolicy implements ExtractPolicy { - private final Logger logger; - - private final static String ASSETS_THUMB_FILENAME = "assetsThumb"; - - public DefaultExtractPolicy(Logger logger) { - this.logger = logger; - } - - public boolean shouldExtract(Context context) { - String assetsThumbFilePath = context.getFilesDir().getPath() + File.separatorChar + ASSETS_THUMB_FILENAME; - String oldAssetsThumb = getCachedAssetsThumb(assetsThumbFilePath); - if (oldAssetsThumb == null) { - return true; - } else { - String currentThumb = getAssetsThumb(context); - - if (currentThumb != null && !currentThumb.equals(oldAssetsThumb)) { - return true; - } - } - - return false; - } - - public void setAssetsThumb(Context context) { - String assetsThumb = generateAssetsThumb(context); - if (assetsThumb != null) { - String assetsThumbFilePath = context.getFilesDir().getPath() + File.separatorChar + ASSETS_THUMB_FILENAME; - saveNewAssetsThumb(assetsThumb, assetsThumbFilePath); - } - } - - public boolean forceOverwrite() { - return true; - } - - public FileExtractor extractor() { - return null; - } - - public String getAssetsThumb(Context context) { - return generateAssetsThumb(context); - } - - private String generateAssetsThumb(Context context) { - try { - PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); - int code = packageInfo.versionCode; - long updateTime = packageInfo.lastUpdateTime; - return String.valueOf(updateTime) + "-" + String.valueOf(code); - } catch (PackageManager.NameNotFoundException e) { - logger.write("Error while getting current assets thumb"); - e.printStackTrace(); - } - - return null; - } - - private String getCachedAssetsThumb(String assetsThumbFilePath) { - try { - File cachedThumbFile = new File(assetsThumbFilePath); - if (cachedThumbFile.exists()) { - FileInputStream in = new FileInputStream(cachedThumbFile); - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - String cachedThumb = reader.readLine(); - reader.close(); - in.close(); - return cachedThumb; - } - } catch (FileNotFoundException e) { - logger.write("Error while getting current assets thumb"); - e.printStackTrace(); - } catch (IOException e) { - logger.write("Error while getting current asstes thumb"); - e.printStackTrace(); - } - - return null; - } - - private void saveNewAssetsThumb(String newThumb, String assetsThumbFile) { - File cachedThumbFile = new File(assetsThumbFile); - try { - FileOutputStream out = new FileOutputStream(cachedThumbFile, false); - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); - try { - writer.write(newThumb); - writer.newLine(); - writer.flush(); - } finally { - writer.close(); - out.close(); - } - } catch (FileNotFoundException e) { - logger.write("Error while writting current assets thumb"); - e.printStackTrace(); - } catch (IOException e) { - logger.write("Error while writting current assets thumb"); - e.printStackTrace(); - } - } - -} diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/LogcatLogger.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/LogcatLogger.java deleted file mode 100644 index 4be958e9c..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/LogcatLogger.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.tns; - -import android.content.Context; -import android.util.Log; - -public final class LogcatLogger implements Logger { - private final static String DEFAULT_LOG_TAG = "TNS.Java"; - - private boolean enabled; - - public LogcatLogger(Context context) { - this.initLogging(context); - } - - public final boolean isEnabled() { - return enabled; - } - - public final void setEnabled(boolean isEnabled) { - enabled = isEnabled; - } - - public final void write(String msg) { - Log.d(DEFAULT_LOG_TAG, msg); - } - - public final void write(String tag, String msg) { - Log.d(tag, msg); - } - - private void initLogging(Context context) { - boolean isDebuggableApp = Util.isDebuggableApp(context); - if (isDebuggableApp) { - String verboseLoggingProp = Util.readSystemProperty("nativescript.verbose.logging"); - - if (Util.isPositive(verboseLoggingProp)) { - setEnabled(true); - } - } - } -} diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/NativeScriptApplication.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/NativeScriptApplication.java deleted file mode 100644 index d8a648753..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/NativeScriptApplication.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.tns; - -import android.app.Application; - -public class NativeScriptApplication extends android.app.Application { - - private static NativeScriptApplication thiz; - - public NativeScriptApplication() { - thiz = this; - } - - public void onCreate() { - ManualInstrumentation.Frame frame = ManualInstrumentation.start("NaitveScriptApplication.onCreate"); - try { - super.onCreate(); - com.tns.Runtime runtime = RuntimeHelper.initRuntime(this); - if (runtime != null) { - runtime.run(); - } - } finally { - frame.close(); - } - } - - public static Application getInstance() { - return thiz; - } -} diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java deleted file mode 100644 index ea8764cf3..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.tns; - -import java.lang.Thread.UncaughtExceptionHandler; - -import android.content.Context; - -public class NativeScriptUncaughtExceptionHandler implements UncaughtExceptionHandler { - private final Context context; - - private final UncaughtExceptionHandler defaultHandler; - - private final Logger logger; - - public NativeScriptUncaughtExceptionHandler(Logger logger, Context context) { - this.logger = logger; - this.context = context; - defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); - } - - @Override - public void uncaughtException(Thread thread, Throwable ex) { - String currentThreadMessage = "An uncaught Exception occurred on \"" + thread.getName() + "\" thread.\n"; - - String errorMessage = currentThreadMessage + getErrorMessage(ex); - - if (Runtime.isInitialized()) { - try { - ex.printStackTrace(); - - Runtime runtime = Runtime.getCurrentRuntime(); - - if (runtime != null) { - runtime.passUncaughtExceptionToJs(ex, errorMessage); - } - } catch (Throwable t) { - t.printStackTrace(); - } - } - - if (logger.isEnabled()) { - logger.write("Uncaught Exception Message=" + errorMessage); - } - - boolean res = false; - - if (Util.isDebuggableApp(context)) { - try { - Class ErrReport = null; - java.lang.reflect.Method startActivity = null; - - ErrReport = java.lang.Class.forName("com.tns.ErrorReport"); - - startActivity = ErrReport.getDeclaredMethod("startActivity", android.content.Context.class, String.class); - - res = (Boolean) startActivity.invoke(null, context, errorMessage); - } catch (Exception e) { - android.util.Log.v("Error", errorMessage); - e.printStackTrace(); - android.util.Log.v("Application Error", "ErrorActivity default implementation not found. Reinstall android platform to fix."); - } - } - - if (!res && defaultHandler != null) { - defaultHandler.uncaughtException(thread, ex); - } - } - - private static String getErrorMessage(Throwable ex) { - String content; - java.io.PrintStream ps = null; - - try { - java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); - ps = new java.io.PrintStream(baos); - ex.printStackTrace(ps); - - try { - content = baos.toString("US-ASCII"); - } catch (java.io.UnsupportedEncodingException e) { - content = e.getMessage(); - } - } finally { - if (ps != null) { - ps.close(); - } - } - - return content; - } -} diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/RuntimeHelper.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/RuntimeHelper.java deleted file mode 100644 index 68efb6d1e..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/RuntimeHelper.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.tns; - -import java.io.File; - -import android.app.Application; -import android.content.Context; -import android.content.pm.PackageManager.NameNotFoundException; -import android.os.Build; -import android.util.Log; - -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public final class RuntimeHelper { - private RuntimeHelper() { - } - - private static AndroidJsV8Inspector v8Inspector; - - // hasErrorIntent tells you if there was an event (with an uncaught - // exception) raised from ErrorReport - private static boolean hasErrorIntent(Application app) { - boolean hasErrorIntent = false; - - try { - // empty file just to check if there was a raised uncaught error by - // ErrorReport - if (Util.isDebuggableApp(app)) { - String fileName = ""; - - try { - Class ErrReport = Class.forName("com.tns.ErrorReport"); - Field field = ErrReport.getDeclaredField("ERROR_FILE_NAME"); - fileName = (String) field.get(null); - } catch (Exception e) { - return false; - } - - File errFile = new File(app.getFilesDir(), fileName); - - if (errFile.exists()) { - errFile.delete(); - hasErrorIntent = true; - } - } - } catch (Exception e) { - Log.d(logTag, e.getMessage()); - } - - return hasErrorIntent; - } - - public static Runtime initRuntime(Application app) { - if (Runtime.isInitialized()) { - return Runtime.getCurrentRuntime(); - } - - ManualInstrumentation.Frame frame = ManualInstrumentation.start("RuntimeHelper.initRuntime"); - try { - ManualInstrumentation.Frame loadLibraryFrame = ManualInstrumentation.start("loadLibrary NativeScript"); - try { - System.loadLibrary("NativeScript"); - } finally { - loadLibraryFrame.close(); - } - - Logger logger = new LogcatLogger(app); - - Runtime runtime = null; - boolean showErrorIntent = hasErrorIntent(app); - if (!showErrorIntent) { - NativeScriptUncaughtExceptionHandler exHandler = new NativeScriptUncaughtExceptionHandler(logger, app); - - Thread.setDefaultUncaughtExceptionHandler(exHandler); - - DefaultExtractPolicy extractPolicy = new DefaultExtractPolicy(logger); - boolean skipAssetExtraction = Util.runPlugin(logger, app); - - String appName = app.getPackageName(); - File rootDir = new File(app.getApplicationInfo().dataDir); - File appDir = app.getFilesDir(); - - try { - appDir = appDir.getCanonicalFile(); - } catch (IOException e1) { - } - - if (!skipAssetExtraction) { - ManualInstrumentation.Frame extractionFrame = ManualInstrumentation.start("Extracting assets"); - try { - if (logger.isEnabled()) { - logger.write("Extracting assets..."); - } - - AssetExtractor aE = new AssetExtractor(null, logger); - - String outputDir = app.getFilesDir().getPath() + File.separator; - - // will force deletion of previously extracted files in app/files directories - // see https://github.com/NativeScript/NativeScript/issues/4137 for reference - boolean removePreviouslyInstalledAssets = true; - aE.extractAssets(app, "app", outputDir, extractPolicy, removePreviouslyInstalledAssets); - aE.extractAssets(app, "internal", outputDir, extractPolicy, removePreviouslyInstalledAssets); - aE.extractAssets(app, "metadata", outputDir, extractPolicy, false); - - boolean shouldExtractSnapshots = true; - - // will extract snapshot of the device appropriate architecture - if (shouldExtractSnapshots) { - if (logger.isEnabled()) { - logger.write("Extracting snapshot blob"); - } - - aE.extractAssets(app, "snapshots/" + Build.CPU_ABI, outputDir, extractPolicy, removePreviouslyInstalledAssets); - } - - extractPolicy.setAssetsThumb(app); - } finally { - extractionFrame.close(); - } - } - - AppConfig appConfig = new AppConfig(appDir); - ManualInstrumentation.setMode(appConfig.getProfilingMode()); - - ClassLoader classLoader = app.getClassLoader(); - File dexDir = new File(rootDir, "code_cache/secondary-dexes"); - String dexThumb = null; - try { - dexThumb = Util.getDexThumb(app); - } catch (NameNotFoundException e) { - if (logger.isEnabled()) { - logger.write("Error while getting current proxy thumb"); - } - e.printStackTrace(); - } - - String nativeLibDir = null; - try { - nativeLibDir = app.getPackageManager().getApplicationInfo(appName, 0).nativeLibraryDir; - } catch (android.content.pm.PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - - boolean isDebuggable = Util.isDebuggableApp(app); - StaticConfiguration config = new StaticConfiguration(logger, appName, nativeLibDir, rootDir, - appDir, classLoader, dexDir, dexThumb, appConfig, isDebuggable); - - runtime = Runtime.initializeRuntimeWithConfiguration(config); - if (isDebuggable) { - try { - v8Inspector = new AndroidJsV8Inspector(app.getFilesDir().getAbsolutePath(), app.getPackageName()); - v8Inspector.start(); - - // the following snippet is used as means to notify the VSCode extension - // debugger that the debugger agent has started - File debuggerStartedFile = new File("/data/local/tmp", app.getPackageName() + "-debugger-started"); - if (debuggerStartedFile.exists() && !debuggerStartedFile.isDirectory() && debuggerStartedFile.length() == 0) { - java.io.FileWriter fileWriter = new java.io.FileWriter(debuggerStartedFile); - fileWriter.write("started"); - fileWriter.close(); - } - - // check if --debug-brk flag has been set. If positive: - // write to the file to invalidate the flag - // inform the v8Inspector to pause the main thread - File debugBreakFile = new File("/data/local/tmp", app.getPackageName() + "-debugbreak"); - boolean shouldBreak = false; - if (debugBreakFile.exists() && !debugBreakFile.isDirectory() && debugBreakFile.length() == 0) { - java.io.FileWriter fileWriter = new java.io.FileWriter(debugBreakFile); - fileWriter.write("started"); - fileWriter.close(); - - shouldBreak = true; - } - - v8Inspector.waitForDebugger(shouldBreak); - } catch (IOException e) { - e.printStackTrace(); - } - - // if app is in debuggable mode run livesync service - // runtime needs to be initialized before the NativeScriptSyncService is enabled because it uses runtime.runScript(...) - try { - Class NativeScriptSyncService = Class.forName("com.tns.NativeScriptSyncService"); - - Constructor cons = NativeScriptSyncService.getConstructor(new Class[] {Runtime.class, Logger.class, Context.class}); - Object syncService = cons.newInstance(runtime, logger, app); - - Method syncMethod = NativeScriptSyncService.getMethod("sync"); - syncMethod.invoke(syncService); - Method startServerMethod = NativeScriptSyncService.getMethod("startServer"); - startServerMethod.invoke(syncService); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } - } - - runtime.runScript(new File(appDir, "internal/ts_helpers.js")); - - File javaClassesModule = new File(appDir, "app/tns-java-classes.js"); - if (javaClassesModule.exists()) { - runtime.runModule(javaClassesModule); - } - - try { - // put this call in a try/catch block because with the latest changes in the modules it is not granted that NativeScriptApplication is extended through JavaScript. - JavaScriptImplementation jsImpl = app.getClass().getAnnotation(JavaScriptImplementation.class); - if (jsImpl != null) { - Runtime.initInstance(app); - } - } catch (Exception e) { - if (logger.isEnabled()) { - logger.write("Cannot initialize application instance."); - } - e.printStackTrace(); - } - } - return runtime; - } finally { - frame.close(); - } - } - - private static final String logTag = "MyApp"; -} diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/Util.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/Util.java deleted file mode 100644 index d55685bc5..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/Util.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.tns; - -import java.io.*; - -import com.tns.internal.Plugin; - -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.os.Bundle; - -public final class Util { - private Util() { - } - - public static String getDexThumb(Context context) throws NameNotFoundException { - PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); - int code = packageInfo.versionCode; - long updateTime = packageInfo.lastUpdateTime; - return String.valueOf(updateTime) + "-" + String.valueOf(code); - } - - public static boolean isDebuggableApp(Context context) { - int flags; - try { - flags = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.flags; - } catch (NameNotFoundException e) { - flags = 0; - e.printStackTrace(); - } - - boolean isDebuggableApp = ((flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); - return isDebuggableApp; - } - - static boolean runPlugin(Logger logger, Context context) { - boolean success = false; - String pluginClassName = "org.nativescript.livesync.LiveSyncPlugin"; - try { - ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); - Bundle metadataBundle = ai.metaData; - if (metadataBundle != null) { - pluginClassName = metadataBundle.getString("com.tns.internal.Plugin"); - } - } catch (Exception e) { - if (logger.isEnabled()) { - e.printStackTrace(); - } - } - - try { - Class liveSyncPluginClass = Class.forName(pluginClassName); - Plugin p = (Plugin) liveSyncPluginClass.newInstance(); - success = p.execute(context); - } catch (Exception e) { - if (logger.isEnabled()) { - e.printStackTrace(); - } - } - return success; - } - - public static String readSystemProperty(String name) { - InputStreamReader in = null; - BufferedReader reader = null; - try { - Process proc = java.lang.Runtime.getRuntime().exec(new String[] { "/system/bin/getprop", name }); - in = new InputStreamReader(proc.getInputStream()); - reader = new BufferedReader(in); - return reader.readLine(); - } catch (IOException e) { - return null; - } finally { - silentClose(in); - silentClose(reader); - } - } - - private static void silentClose(Closeable closeable) { - if (closeable == null) { - return; - } - try { - closeable.close(); - } catch (IOException ignored) { - } - } - - public static Boolean isPositive(String value) { - if (value == null) { - return false; - } - - return (value.equals("true") || value.equals("TRUE") || - value.equals("yes") || value.equals("YES") || - value.equals("enabled") || value.equals("ENABLED")); - } -} diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/internal/AppBuilderCallback.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/internal/AppBuilderCallback.java deleted file mode 100644 index b99ce172c..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/internal/AppBuilderCallback.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.tns.internal; - -import com.tns.ExtractPolicy; - -public interface AppBuilderCallback { - void onConfigurationChanged(android.content.Context context, android.content.res.Configuration newConfig); - - void onCreate(android.content.Context context); - - void onLowMemory(android.content.Context context); - - void onTerminate(android.content.Context context); - - void onTrimMemory(android.content.Context context, int level); - - Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(); - - ExtractPolicy getExtractPolicy(); - - boolean shouldEnableDebugging(android.content.Context context); -} diff --git a/build-artifacts/project-template-gradle/src/main/java/com/tns/internal/Plugin.java b/build-artifacts/project-template-gradle/src/main/java/com/tns/internal/Plugin.java deleted file mode 100644 index b678681f8..000000000 --- a/build-artifacts/project-template-gradle/src/main/java/com/tns/internal/Plugin.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.tns.internal; - -public interface Plugin { - boolean execute(android.content.Context context) throws Exception; -} diff --git a/build.gradle b/build.gradle index 57d8e3bbe..ccd053e9e 100644 --- a/build.gradle +++ b/build.gradle @@ -47,6 +47,33 @@ task createDistDir << { distF.mkdirs() } +task copyFilesToProjectTemeplate << { + copy { + from "$rootDir/test-app/app/src/main/java/com/tns/ErrorReport.java" + from "$rootDir/test-app/app/src/main/java/com/tns/ErrorReportActivity.java" + from "$rootDir/test-app/app/src/main/java/com/tns/NativeScriptSyncService.java" + into "$rootDir/build-artifacts/project-template-gradle/src/debug/java/com/tns/" + } + copy { + from "$rootDir/test-app/app/src/main/assets/internal" + into "$rootDir/build-artifacts/project-template-gradle/src/main/assets/internal" + } + copy { + from "$rootDir/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java" + from "$rootDir/test-app/app/src/main/java/com/tns/DefaultExtractPolicy.java" + from "$rootDir/test-app/app/src/main/java/com/tns/LogcatLogger.java" + from "$rootDir/test-app/app/src/main/java/com/tns/NativeScriptApplication.java" + from "$rootDir/test-app/app/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java" + from "$rootDir/test-app/app/src/main/java/com/tns/RuntimeHelper.java" + from "$rootDir/test-app/app/src/main/java/com/tns/Util.java" + into "$rootDir/build-artifacts/project-template-gradle/src/main/java/com/tns/" + } + copy { + from "$rootDir/test-app/app/src/main/java/com/tns/internal" + into "$rootDir/build-artifacts/project-template-gradle/src/main/java/com/tns/internal" + } +} + task copyProjectTemplate (type: Copy) { from "$rootDir/build-artifacts/project-template-gradle" into "$rootDir/dist/framework" @@ -252,14 +279,21 @@ task copyReadme (type: Copy) { into "$rootDir/dist" } +task cleanBuildArtefacts (type: Delete) { + delete "$rootDir/build-artifacts/project-template-gradle/src/debug/java" + delete "$rootDir/build-artifacts/project-template-gradle/src/main/java" + delete "$rootDir/build-artifacts/project-template-gradle/src/main/assets" +} + //clean and set up dirs -createDistDir.dependsOn(cleanDistDir) +copyFilesToProjectTemeplate.dependsOn(cleanDistDir) //copy framework structure +createDistDir.dependsOn(copyFilesToProjectTemeplate) copyProjectTemplate.dependsOn(createDistDir) copyPackageJson.dependsOn(copyProjectTemplate) -copyStaticBindingGeneratorProject.dependsOn(copyProjectTemplate) +copyStaticBindingGeneratorProject.dependsOn(copyPackageJson) //generate static binding generator and copy into project template generateInterfaceNameGenerator.dependsOn(copyStaticBindingGeneratorProject) copyInterfaceNameGeneratorJar.dependsOn(generateInterfaceNameGenerator) @@ -267,7 +301,7 @@ generateStaticBindingGeneratorJar.dependsOn(copyInterfaceNameGeneratorJar) copyGeneratedStaticBindingGeneratorJar.dependsOn(generateStaticBindingGeneratorJar) //get version from package json -getPackageVersion.dependsOn(copyProjectTemplate) +getPackageVersion.dependsOn(copyGeneratedStaticBindingGeneratorJar) getCommitVersion.dependsOn(getPackageVersion) //generate runtime and copy into framework structure @@ -294,7 +328,9 @@ copyGeneratedMetadataGeneratorJar.dependsOn(generateMetadataGeneratorJar) copyReadme.dependsOn(copyGeneratedMetadataGeneratorJar) //pack runtime -createNpmPackage.dependsOn(copyReadme, setPackageVersionInPackageJsonFile) +setPackageVersionInPackageJsonFile.dependsOn(copyReadme) +createNpmPackage.dependsOn(setPackageVersionInPackageJsonFile) +cleanBuildArtefacts.dependsOn(createNpmPackage) task createPackage { description "Builds the NativeScript Android App Package using an application project template." @@ -320,7 +356,8 @@ task createPackage { generateMetadataGeneratorJar, copyGeneratedMetadataGeneratorJar, copyReadme, - createNpmPackage + createNpmPackage, + cleanBuildArtefacts println "Creating NativeScript Android Package" } diff --git a/test-app/app/src/main/assets/internal/ts_helpers.js b/test-app/app/src/main/assets/internal/ts_helpers.js index 2175f563f..aba1778fd 100644 --- a/test-app/app/src/main/assets/internal/ts_helpers.js +++ b/test-app/app/src/main/assets/internal/ts_helpers.js @@ -1,6 +1,9 @@ (function() { var __extends_ts = function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + if (!b.extend) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + } + function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); diff --git a/test-app/app/src/main/java/com/tns/NativeScriptApplication.java b/test-app/app/src/main/java/com/tns/NativeScriptApplication.java index e347da5c9..d8a648753 100644 --- a/test-app/app/src/main/java/com/tns/NativeScriptApplication.java +++ b/test-app/app/src/main/java/com/tns/NativeScriptApplication.java @@ -1,7 +1,6 @@ package com.tns; import android.app.Application; -import android.os.Debug; public class NativeScriptApplication extends android.app.Application { diff --git a/test-app/app/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java b/test-app/app/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java index fd30e0009..ea8764cf3 100644 --- a/test-app/app/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java +++ b/test-app/app/src/main/java/com/tns/NativeScriptUncaughtExceptionHandler.java @@ -21,7 +21,7 @@ public NativeScriptUncaughtExceptionHandler(Logger logger, Context context) { public void uncaughtException(Thread thread, Throwable ex) { String currentThreadMessage = "An uncaught Exception occurred on \"" + thread.getName() + "\" thread.\n"; - String errorMessage = currentThreadMessage + ErrorReport.getErrorMessage(ex); + String errorMessage = currentThreadMessage + getErrorMessage(ex); if (Runtime.isInitialized()) { try { @@ -41,8 +41,50 @@ public void uncaughtException(Thread thread, Throwable ex) { logger.write("Uncaught Exception Message=" + errorMessage); } - if (!ErrorReport.startActivity(context, errorMessage) && defaultHandler != null) { + boolean res = false; + + if (Util.isDebuggableApp(context)) { + try { + Class ErrReport = null; + java.lang.reflect.Method startActivity = null; + + ErrReport = java.lang.Class.forName("com.tns.ErrorReport"); + + startActivity = ErrReport.getDeclaredMethod("startActivity", android.content.Context.class, String.class); + + res = (Boolean) startActivity.invoke(null, context, errorMessage); + } catch (Exception e) { + android.util.Log.v("Error", errorMessage); + e.printStackTrace(); + android.util.Log.v("Application Error", "ErrorActivity default implementation not found. Reinstall android platform to fix."); + } + } + + if (!res && defaultHandler != null) { defaultHandler.uncaughtException(thread, ex); } } + + private static String getErrorMessage(Throwable ex) { + String content; + java.io.PrintStream ps = null; + + try { + java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); + ps = new java.io.PrintStream(baos); + ex.printStackTrace(ps); + + try { + content = baos.toString("US-ASCII"); + } catch (java.io.UnsupportedEncodingException e) { + content = e.getMessage(); + } + } finally { + if (ps != null) { + ps.close(); + } + } + + return content; + } } diff --git a/test-app/app/src/main/res/layout/error_activity.xml b/test-app/app/src/main/res/layout/error_activity.xml index 3007cde32..8720947cf 100644 --- a/test-app/app/src/main/res/layout/error_activity.xml +++ b/test-app/app/src/main/res/layout/error_activity.xml @@ -11,8 +11,7 @@ android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" - android:minHeight="?attr/actionBarSize" - android:layout_alignBottom="@+id/tabLayout"/> + android:minHeight="?attr/actionBarSize"/> + tools:layout_width="match_parent"/> Date: Fri, 11 Aug 2017 14:41:18 +0300 Subject: [PATCH 2/2] commet out test, because of lack of usage by users --- .../assets/app/tests/testsForTypescript.js | 89 ++++++++++--------- 1 file changed, 46 insertions(+), 43 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testsForTypescript.js b/test-app/app/src/main/assets/app/tests/testsForTypescript.js index 93298f03c..35065f3af 100644 --- a/test-app/app/src/main/assets/app/tests/testsForTypescript.js +++ b/test-app/app/src/main/assets/app/tests/testsForTypescript.js @@ -334,80 +334,83 @@ describe("Tests typescript", function () { expect(errorThrown).toEqual(true); }); - - it("When_accessing_a_static_field_on_a_typescript_instance_it_should_work", function () { - - __log("TEST: When_accessing_a_static_field_on_a_typescript_instance_it_should_work"); - - var MyButton7 = (function (_super) { - __extends(MyButton7, _super); - function MyButton7() { - _super.call(this); - this.my1 = "MyName"; - } - - MyButton7.prototype.init = function () { - }; - MyButton7.prototype.toString = function (s) { - return "my"; - }; - - return MyButton7; - })(com.tns.tests.Button1); - - var valueUsingChild = MyButton7.STATIC_IMAGE_ID; - expect(valueUsingChild).toEqual("static image id"); - - MyButton7.STATIC_IMAGE_ID = "test"; - valueUsingChild = MyButton7.STATIC_IMAGE_ID; - expect(valueUsingChild).toEqual("test"); - - var valueUsingParent = com.tns.tests.Button1.STATIC_IMAGE_ID; - expect(valueUsingParent).toEqual("static image id"); - }); - + // currently dissabled because of: https://github.com/NativeScript/android-runtime/issues/626 + // if propper (check if access is possible on current device) solution is implemented uncomment tests + // for now the users are not using this, and there are no issues about it +// it("When_accessing_a_static_field_on_a_typescript_instance_it_should_work", function () { +// +// __log("TEST: When_accessing_a_static_field_on_a_typescript_instance_it_should_work"); +// +// var MyButton7 = (function (_super) { +// __extends(MyButton7, _super); +// function MyButton7() { +// _super.call(this); +// this.my1 = "MyName"; +// } +// +// MyButton7.prototype.init = function () { +// }; +// +// MyButton7.prototype.toString = function (s) { +// return "my"; +// }; +// +// return MyButton7; +// })(com.tns.tests.Button1); +// +// var valueUsingChild = MyButton7.STATIC_IMAGE_ID; +// expect(valueUsingChild).toEqual("static image id"); +// +// MyButton7.STATIC_IMAGE_ID = "test"; +// valueUsingChild = MyButton7.STATIC_IMAGE_ID; +// expect(valueUsingChild).toEqual("test"); +// +// var valueUsingParent = com.tns.tests.Button1.STATIC_IMAGE_ID; +// expect(valueUsingParent).toEqual("static image id"); +// }); + it("When_calling_a_static_method_on_a_typescript_instance_it_should_work", function () { - + __log("TEST: When_calling_a_static_method_on_a_typescript_instance_it_should_work"); - + var MyButton8 = (function (_super) { __extends(MyButton8, _super); function MyButton8() { _super.call(this); this.my1 = "MyName"; } - + MyButton8.prototype.init = function () { }; MyButton8.prototype.onClick = function () { __log("MyButton onClick called"); }; - + MyButton8.prototype.superToString = function () { return _super.prototype.toString.call(this); }; - + MyButton8.prototype.echo = function (s) { return "echo: " + this.my1; }; - + return MyButton8; })(com.tns.tests.Button1); - + MyButton8.setMyStaticIntField(5); var valueUsingChild = MyButton8.getMyStaticIntField(); expect(valueUsingChild).toEqual(5); - - var valueUsingParent = com.tns.tests.Button1.getMyStaticIntField(); + + var valueUsingParent = com.tns.tests.Button1.getMyStaticIntField(); expect(valueUsingParent).toEqual(5); - + com.tns.tests.Button1.setMyStaticIntField(6); var valueUsingParent = com.tns.tests.Button1.getMyStaticIntField(); expect(valueUsingParent).toEqual(6); - + valueUsingChild = MyButton8.getMyStaticIntField(); expect(valueUsingChild).toEqual(6); });