/*
 * Copyright 2012-2014 JetBrains s.r.o
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jetbrains.jetpad.model.event;


import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

public class Callbacks {
  private static boolean ourForceProduction;
  private static SimpleEventSource<Throwable> ourCallbackExceptions = new SimpleEventSource<>();

  public static EventSource<Throwable> callbackExceptions() {
    return ourCallbackExceptions;
  }

  public static void asInProduction(Runnable r) {
    if (ourForceProduction) {
      throw new IllegalStateException();
    }
    ourForceProduction = true;
    PrintStream oldErr = System.err;
    System.setErr(new PrintStream(new OutputStream() {
      @Override
      public void write(int b) throws IOException {
      }
    }));

    try {
      r.run();
    } finally {
      ourForceProduction = false;
      System.setErr(oldErr);
    }
  }

  public static void handleException(Throwable t) {
    if (isInUnitTests(t)) {
      throw new RuntimeException(t);
    }
    ourCallbackExceptions.fire(t);
    t.printStackTrace();
  }

  private static boolean isInUnitTests(Throwable t) {
    if (ourForceProduction) {
      return false;
    }
    for (StackTraceElement e : t.getStackTrace()) {
      if (e.getClassName().startsWith("org.junit.runners")) {
        return true;
      }
    }
    return false;
  }
}
@@ -639,94 +639,8 @@
 ;%0A%0A%0A
-import java.io.IOException;%0Aimport java.io.OutputStream;%0Aimport java.io.PrintStream;%0A%0A
 publ
@@ -1066,186 +1066,8 @@
 ue;%0A
-    PrintStream oldErr = System.err;%0A    System.setErr(new PrintStream(new OutputStream() %7B%0A      @Override%0A      public void write(int b) throws IOException %7B%0A      %7D%0A    %7D));%0A%0A
     
@@ -1141,37 +1141,8 @@
 se;%0A
-      System.setErr(oldErr);%0A
     

Revert "turn output off for Callbacks test usages"