Merge "ui: Open .trace systrace files directly in legacy UI"
diff --git a/ui/src/frontend/legacy_trace_viewer.ts b/ui/src/frontend/legacy_trace_viewer.ts
index c55451d..253d6af 100644
--- a/ui/src/frontend/legacy_trace_viewer.ts
+++ b/ui/src/frontend/legacy_trace_viewer.ts
@@ -18,12 +18,48 @@
 
 import {globals} from './globals';
 
-export function isLegacyTrace(fileName: string): boolean {
-  fileName = fileName.toLowerCase();
-  return (
-      fileName.endsWith('.json') || fileName.endsWith('.json.gz') ||
+function readText(blob: Blob): Promise<string> {
+  return new Promise((resolve, reject) => {
+    const reader = new FileReader();
+    reader.onload = () => {
+      if (typeof reader.result === 'string') {
+        return resolve(reader.result);
+      }
+    };
+    reader.onerror = err => {
+      reject(err);
+    };
+    reader.readAsText(blob);
+  });
+}
+
+export async function isLegacyTrace(file: File): Promise<boolean> {
+  const fileName = file.name.toLowerCase();
+  if (fileName.endsWith('.json') || fileName.endsWith('.json.gz') ||
       fileName.endsWith('.zip') || fileName.endsWith('.ctrace') ||
-      fileName.endsWith('.html'));
+      fileName.endsWith('.html')) {
+    return true;
+  }
+
+  // Sometimes systrace formatted traces end with '.trace'. This is a
+  // little generic to assume all such traces are systrace format though
+  // so we read the beginning of the file and check to see if is has the
+  // systrace header (several comment lines):
+  if (fileName.endsWith('.trace')) {
+    const header = await readText(file.slice(0, 512));
+    const lines = header.split('\n');
+    let commentCount = 0;
+    for (const line of lines) {
+      if (line.startsWith('#')) {
+        commentCount++;
+      }
+    }
+    if (commentCount > 5) {
+      return true;
+    }
+  }
+
+  return false;
 }
 
 export function openFileWithLegacyTraceViewer(file: File) {
diff --git a/ui/src/frontend/sidebar.ts b/ui/src/frontend/sidebar.ts
index cfeeec5..a295a75 100644
--- a/ui/src/frontend/sidebar.ts
+++ b/ui/src/frontend/sidebar.ts
@@ -311,12 +311,7 @@
   globals.frontendLocalState.localOnlyMode = false;
 
   if (e.target.dataset['useCatapultLegacyUi'] === '1') {
-    // Switch back to the old catapult UI.
-    if (isLegacyTrace(file.name)) {
-      openFileWithLegacyTraceViewer(file);
-      return;
-    }
-    openInOldUIWithSizeCheck(file);
+    openWithLegacyUi(file);
     return;
   }
 
@@ -343,7 +338,15 @@
   }
 
   globals.dispatch(Actions.openTraceFromFile({file}));
+}
 
+async function openWithLegacyUi(file: File) {
+  // Switch back to the old catapult UI.
+  if (await isLegacyTrace(file)) {
+    openFileWithLegacyTraceViewer(file);
+    return;
+  }
+  openInOldUIWithSizeCheck(file);
 }
 
 function openInOldUIWithSizeCheck(trace: Blob) {