text:
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package io.flutter.embedding.android;

import static android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.DEFAULT_INITIAL_ROUTE;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.lifecycle.Lifecycle;
import io.flutter.FlutterInjector;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.FlutterShellArgs;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener;
import io.flutter.plugin.platform.PlatformPlugin;
import io.flutter.util.ViewUtils;
import java.util.Arrays;
import java.util.List;

/**
 * Delegate that implements all Flutter logic that is the same between a {@link FlutterActivity} and
 * a {@link FlutterFragment}.
 *
 *
Why does this class exist?
 *
 *
One might ask why an {@code Activity} and {@code Fragment} delegate needs to exist. Given that
 * a {@code Fragment} can be placed within an {@code Activity}, it would make more sense to use a
 * {@link FlutterFragment} within a {@link FlutterActivity}.
 *
 *
The {@code Fragment} support library adds 100k of binary size to an app, and full-Flutter apps
 * do not otherwise require that binary hit. Therefore, it was concluded that Flutter must provide a
 * {@link FlutterActivity} based on the AOSP {@code Activity}, and an independent {@link
 * FlutterFragment} for add-to-app developers.
 *
 *
If a time ever comes where the inclusion of {@code Fragment}s in a full-Flutter app is no
 * longer deemed an issue, this class should be immediately decomposed between {@link
 * FlutterActivity} and {@link FlutterFragment} and then eliminated.
 *
 *
Caution when modifying this class
 *
 *
Any time that a "delegate" is created with the purpose of encapsulating the internal behaviors
 * of another object, that delegate is highly susceptible to degeneration. It is easy to tack new
 * responsibilities on to the delegate which would not otherwise be added to the original object. It
 * is also easy to begin hanging listeners and callbacks on a delegate object that likewise would
 * not be added to the original object. A delegate can quickly become a complex web of dependencies
 * and optional references that are very difficult to track.
 *
 *
Maintainers of this class should take care to only place code in this delegate that would
 * otherwise be placed in either {@link FlutterActivity} or {@link FlutterFragment}, and in exactly
 * the same form. Do not use this class as a convenient shortcut for any other
 * behavior.
 */
/* package */ class FlutterActivityAndFragmentDelegate implements ExclusiveAppComponent<Activity> {
  private static final String TAG = "FlutterActivityAndFragmentDelegate";
  private static final String FRAMEWORK_RESTORATION_BUNDLE_KEY = "framework";
  private static final String PLUGINS_RESTORATION_BUNDLE_KEY = "plugins";
  private static final int FLUTTER_SPLASH_VIEW_FALLBACK_ID = 486947586;

  /** Factory to obtain a FlutterActivityAndFragmentDelegate instance. */
  public interface DelegateFactory {
    FlutterActivityAndFragmentDelegate createDelegate(FlutterActivityAndFragmentDelegate.Host host);
  }

  // The FlutterActivity or FlutterFragment that is delegating most of its calls
  // to this FlutterActivityAndFragmentDelegate.
  @NonNull private Host host;
  @Nullable private FlutterEngine flutterEngine;
  @VisibleForTesting @Nullable FlutterView flutterView;
  @Nullable private PlatformPlugin platformPlugin;
  @VisibleForTesting @Nullable OnPreDrawListener activePreDrawListener;
  private boolean isFlutterEngineFromHost;
  private boolean isFlutterUiDisplayed;
  private boolean isFirstFrameRendered;
  private boolean isAttached;
  private Integer previousVisibility;

  @NonNull
  private final FlutterUiDisplayListener flutterUiDisplayListener =
      new FlutterUiDisplayListener() {
        @Override
        public void onFlutterUiDisplayed() {
          host.onFlutterUiDisplayed();
          isFlutterUiDisplayed = true;
          isFirstFrameRendered = true;
        }

        @Override
        public void onFlutterUiNoLongerDisplayed() {
          host.onFlutterUiNoLongerDisplayed();
          isFlutterUiDisplayed = false;
        }
      };

  FlutterActivityAndFragmentDelegate(@NonNull Host host) {
    this.host = host;
    this.isFirstFrameRendered = false;
  }

  /**
   * Disconnects this {@code FlutterActivityAndFragmentDelegate} from its host {@code Activity} or
   * {@code Fragment}.
   *
   *
No further method invocations may occur on this {@code FlutterActivityAndFragmentDelegate}
   * after invoking this method. If a method is invoked, an exception will occur.
   *
   *
This method only clears out references. It does not destroy its {@link
   * io.flutter.embedding.engine.FlutterEngine}. The behavior that destroys a {@link
   * io.flutter.embedding.engine.FlutterEngine} can be found in {@link #onDetach()}.
   */
  void release() {
    this.host = null;
    this.flutterEngine = null;
    this.flutterView = null;
    this.platformPlugin = null;
  }

  /**
   * Returns the {@link io.flutter.embedding.engine.FlutterEngine} that is owned by this delegate
   * and its host {@code Activity} or {@code Fragment}.
   */
  @Nullable
  /* package */ FlutterEngine getFlutterEngine() {
    return flutterEngine;
  }

  /**
   * Returns true if the host {@code Activity}/{@code Fragment} provided a {@code FlutterEngine}, as
   * opposed to this delegate creating a new one.
   */
  /* package */ boolean isFlutterEngineFromHost() {
    return isFlutterEngineFromHost;
  }

  /**
   * Whether or not this {@code FlutterActivityAndFragmentDelegate} is attached to a {@code
   * FlutterEngine}.
   */
  /* package */ boolean isAttached() {
    return isAttached;
  }

  /**
   * Invoke this method from {@code Activity#onCreate(Bundle)} or {@code
   * Fragment#onAttach(Context)}.
   *
   *
This method does the following:
   *
   *

   *
   *

   *
Initializes the Flutter system.
   *
Obtains or creates a {@link io.flutter.embedding.engine.FlutterEngine}.
   *
Creates and configures a {@link PlatformPlugin}.
   *
Attaches the {@link io.flutter.embedding.engine.FlutterEngine} to the surrounding {@code
   *       Activity}, if desired.
   *
Configures the {@link io.flutter.embedding.engine.FlutterEngine} via {@link
   *       Host#configureFlutterEngine(FlutterEngine)}.
   *

   */
  void onAttach(@NonNull Context context) {
    ensureAlive();

    // When "retain instance" is true, the FlutterEngine will survive configuration
    // changes. Therefore, we create a new one only if one does not already exist.
    if (flutterEngine == null) {
      setupFlutterEngine();
    }

    if (host.shouldAttachEngineToActivity()) {
      // Notify any plugins that are currently attached to our FlutterEngine that they
      // are now attached to an Activity.
      //
      // Passing this Fragment's Lifecycle should be sufficient because as long as this Fragment
      // is attached to its Activity, the lifecycles should be in sync. Once this Fragment is
      // detached from its Activity, that Activity will be detached from the FlutterEngine, too,
      // which means there shouldn't be any possibility for the Fragment Lifecycle to get out of
      // sync with the Activity. We use the Fragment's Lifecycle because it is possible that the
      // attached Activity is not a LifecycleOwner.
      Log.v(TAG, "Attaching FlutterEngine to the Activity that owns this delegate.");
      flutterEngine.getActivityControlSurface().attachToActivity(this, host.getLifecycle());
    }

    // Regardless of whether or not a FlutterEngine already existed, the PlatformPlugin
    // is bound to a specific Activity. Therefore, it needs to be created and configured
    // every time this Fragment attaches to a new Activity.
    // TODO(mattcarroll): the PlatformPlugin needs to be reimagined because it implicitly takes
    //                    control of the entire window. This is unacceptable for non-fullscreen
    //                    use-cases.
    platformPlugin = host.providePlatformPlugin(host.getActivity(), flutterEngine);

    host.configureFlutterEngine(flutterEngine);
    isAttached = true;
  }

  @Override
  public @NonNull Activity getAppComponent() {
    final Activity activity = host.getActivity();
    if (activity == null) {
      throw new AssertionError(
          "FlutterActivityAndFragmentDelegate's getAppComponent should only "
              + "be queried after onAttach, when the host's activity should always be non-null");
    }
    return activity;
  }

  /**
   * Obtains a reference to a FlutterEngine to back this delegate and its {@code host}.
   *
   *

   *
   *
First, the {@code host} is asked if it would like to use a cached {@link
   * io.flutter.embedding.engine.FlutterEngine}, and if so, the cached {@link
   * io.flutter.embedding.engine.FlutterEngine} is retrieved.
   *
   *
Second, the {@code host} is given an opportunity to provide a {@link
   * io.flutter.embedding.engine.FlutterEngine} via {@link Host#provideFlutterEngine(Context)}.
   *
   *
If the {@code host} does not provide a {@link io.flutter.embedding.engine.FlutterEngine},
   * then a new {@link FlutterEngine} is instantiated.
   */
  @VisibleForTesting
  /* package */ void setupFlutterEngine() {
    Log.v(TAG, "Setting up FlutterEngine.");

    // First, check if the host wants to use a cached FlutterEngine.
    String cachedEngineId = host.getCachedEngineId();
    if (cachedEngineId != null) {
      flutterEngine = FlutterEngineCache.getInstance().get(cachedEngineId);
      isFlutterEngineFromHost = true;
      if (flutterEngine == null) {
        throw new IllegalStateException(
            "The requested cached FlutterEngine did not exist in the FlutterEngineCache: '"
                + cachedEngineId
                + "'");
      }
      return;
    }

    // Second, defer to subclasses for a custom FlutterEngine.
    flutterEngine = host.provideFlutterEngine(host.getContext());
    if (flutterEngine != null) {
      isFlutterEngineFromHost = true;
      return;
    }

    // Our host did not provide a custom FlutterEngine. Create a FlutterEngine to back our
    // FlutterView.
    Log.v(
        TAG,
        "No preferred FlutterEngine was provided. Creating a new FlutterEngine for"
            + " this FlutterFragment.");
    flutterEngine =
        new FlutterEngine(
            host.getContext(),
            host.getFlutterShellArgs().toArray(),
            /*automaticallyRegisterPlugins=*/ false,
            /*willProvideRestorationData=*/ host.shouldRestoreAndSaveState());
    isFlutterEngineFromHost = false;
  }

  /**
   * Invoke this method from {@code Activity#onCreate(Bundle)} to create the content {@code View},
   * or from {@code Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}.
   *
   *
{@code inflater} and {@code container} may be null when invoked from an {@code Activity}.
   *
   *
{@code shouldDelayFirstAndroidViewDraw} determines whether to set up an {@link
   * android.view.ViewTreeObserver.OnPreDrawListener}, which will defer the current drawing pass
   * till after the Flutter UI has been displayed. This results in more accurate timings reported
   * with Android tools, such as "Displayed" timing printed with `am start`.
   *
   *
Note that it should only be set to true when {@code Host#getRenderMode()} is {@code
   * RenderMode.surface}. This parameter is also ignored, disabling the delay should the legacy
   * {@code Host#provideSplashScreen()} be non-null. See Android Splash Migration.
   *
   *
This method:
   *
   *

   *
creates a new {@link FlutterView} in a {@code View} hierarchy
   *
adds a {@link FlutterUiDisplayListener} to it
   *
attaches a {@link io.flutter.embedding.engine.FlutterEngine} to the new {@link
   *       FlutterView}
   *
returns the new {@code View} hierarchy
   *

   */
  @NonNull
  View onCreateView(
      LayoutInflater inflater,
      @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState,
      int flutterViewId,
      boolean shouldDelayFirstAndroidViewDraw) {
    Log.v(TAG, "Creating FlutterView.");
    ensureAlive();

    if (host.getRenderMode() == RenderMode.surface) {
      FlutterSurfaceView flutterSurfaceView =
          new FlutterSurfaceView(
              host.getContext(), host.getTransparencyMode() == TransparencyMode.transparent);

      // Allow our host to customize FlutterSurfaceView, if desired.
      host.onFlutterSurfaceViewCreated(flutterSurfaceView);

      // Create the FlutterView that owns the FlutterSurfaceView.
      flutterView = new FlutterView(host.getContext(), flutterSurfaceView);
    } else {
      FlutterTextureView flutterTextureView = new FlutterTextureView(host.getContext());

      flutterTextureView.setOpaque(host.getTransparencyMode() == TransparencyMode.opaque);

      // Allow our host to customize FlutterSurfaceView, if desired.
      host.onFlutterTextureViewCreated(flutterTextureView);

      // Create the FlutterView that owns the FlutterTextureView.
      flutterView = new FlutterView(host.getContext(), flutterTextureView);
    }

    // Add listener to be notified when Flutter renders its first frame.
    flutterView.addOnFirstFrameRenderedListener(flutterUiDisplayListener);

    Log.v(TAG, "Attaching FlutterEngine to FlutterView.");
    flutterView.attachToFlutterEngine(flutterEngine);
    flutterView.setId(flutterViewId);

    SplashScreen splashScreen = host.provideSplashScreen();

    if (splashScreen != null) {
      Log.w(
          TAG,
          "A splash screen was provided to Flutter, but this is deprecated. See"
              + " flutter.dev/go/android-splash-migration for migration steps.");
      FlutterSplashView flutterSplashView = new FlutterSplashView(host.getContext());
      flutterSplashView.setId(ViewUtils.generateViewId(FLUTTER_SPLASH_VIEW_FALLBACK_ID));
      flutterSplashView.displayFlutterViewWithSplash(flutterView, splashScreen);

      return flutterSplashView;
    }

    if (shouldDelayFirstAndroidViewDraw) {
      delayFirstAndroidViewDraw(flutterView);
    }
    return flutterView;
  }

  void onRestoreInstanceState(@Nullable Bundle bundle) {
    Log.v(
        TAG,
        "onRestoreInstanceState. Giving framework and plugins an opportunity to restore state.");
    ensureAlive();

    Bundle pluginState = null;
    byte[] frameworkState = null;
    if (bundle != null) {
      pluginState = bundle.getBundle(PLUGINS_RESTORATION_BUNDLE_KEY);
      frameworkState = bundle.getByteArray(FRAMEWORK_RESTORATION_BUNDLE_KEY);
    }

    if (host.shouldRestoreAndSaveState()) {
      flutterEngine.getRestorationChannel().setRestorationData(frameworkState);
    }

    if (host.shouldAttachEngineToActivity()) {
      flutterEngine.getActivityControlSurface().onRestoreInstanceState(pluginState);
    }
  }

  /**
   * Invoke this from {@code Activity#onStart()} or {@code Fragment#onStart()}.
   *
   *
This method:
   *
   *

   *
   *

   *
Begins executing Dart code, if it is not already executing.
   *

   */
  void onStart() {
    Log.v(TAG, "onStart()");
    ensureAlive();
    doInitialFlutterViewRun();
    // This is a workaround for a bug on some OnePlus phones. The visibility of the application
    // window is still true after locking the screen on some OnePlus phones, and shows a black
    // screen when unlocked. We can work around this by changing the visibility of FlutterView in
    // onStart and onStop.
    // See https://github.com/flutter/flutter/issues/93276
    if (previousVisibility != null) {
      flutterView.setVisibility(previousVisibility);
    }
  }

  /**
   * Starts running Dart within the FlutterView for the first time.
   *
   *
Reloading/restarting Dart within a given FlutterView is not supported. If this method is
   * invoked while Dart is already executing then it does nothing.
   *
   *
{@code flutterEngine} must be non-null when invoking this method.
   */
  private void doInitialFlutterViewRun() {
    // Don't attempt to start a FlutterEngine if we're using a cached FlutterEngine.
    if (host.getCachedEngineId() != null) {
      return;
    }

    if (flutterEngine.getDartExecutor().isExecutingDart()) {
      // No warning is logged because this situation will happen on every config
      // change if the developer does not choose to retain the Fragment instance.
      // So this is expected behavior in many cases.
      return;
    }
    String initialRoute = host.getInitialRoute();
    if (initialRoute == null) {
      initialRoute = maybeGetInitialRouteFromIntent(host.getActivity().getIntent());
      if (initialRoute == null) {
        initialRoute = DEFAULT_INITIAL_ROUTE;
      }
    }
    @Nullable String libraryUri = host.getDartEntrypointLibraryUri();
    Log.v(
        TAG,
        "Executing Dart entrypoint: "
                    + host.getDartEntrypointFunctionName()
                    + ", library uri: "
                    + libraryUri
                == null
            ? "\"\""
            : libraryUri + ", and sending initial route: " + initialRoute);

    // The engine needs to receive the Flutter app's initial route before executing any
    // Dart code to ensure that the initial route arrives in time to be applied.
    flutterEngine.getNavigationChannel().setInitialRoute(initialRoute);

    String appBundlePathOverride = host.getAppBundlePath();
    if (appBundlePathOverride == null || appBundlePathOverride.isEmpty()) {
      appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath();
    }

    // Configure the Dart entrypoint and execute it.
    DartExecutor.DartEntrypoint entrypoint =
        libraryUri == null
            ? new DartExecutor.DartEntrypoint(
                appBundlePathOverride, host.getDartEntrypointFunctionName())
            : new DartExecutor.DartEntrypoint(
                appBundlePathOverride, libraryUri, host.getDartEntrypointFunctionName());
    flutterEngine.getDartExecutor().executeDartEntrypoint(entrypoint, host.getDartEntrypointArgs());
  }

  private String maybeGetInitialRouteFromIntent(Intent intent) {
    if (host.shouldHandleDeeplinking()) {
      Uri data = intent.getData();
      if (data != null) {
        String fullRoute = data.getPath();
        if (fullRoute != null && !fullRoute.isEmpty()) {
          if (data.getQuery() != null && !data.getQuery().isEmpty()) {
            fullRoute += "?" + data.getQuery();
          }
          if (data.getFragment() != null && !data.getFragment().isEmpty()) {
            fullRoute += "#" + data.getFragment();
          }
          return fullRoute;
        }
      }
    }
    return null;
  }

  /**
   * Delays the first drawing of the {@code flutterView} until the Flutter first has been displayed.
   */
  private void delayFirstAndroidViewDraw(FlutterView flutterView) {
    if (host.getRenderMode() != RenderMode.surface) {
      // Using a TextureView will cause a deadlock, where the underlying SurfaceTexture is never
      // available since it will wait for drawing to be completed first. At the same time, the
      // preDraw listener keeps returning false since the Flutter Engine waits for the
      // SurfaceTexture to be available.
      throw new IllegalArgumentException(
          "Cannot delay the first Android view draw when the render mode is not set to"
              + " `RenderMode.surface`.");
    }

    if (activePreDrawListener != null) {
      flutterView.getViewTreeObserver().removeOnPreDrawListener(activePreDrawListener);
    }

    activePreDrawListener =
        new OnPreDrawListener() {
          @Override
          public boolean onPreDraw() {
            if (isFlutterUiDisplayed && activePreDrawListener != null) {
              flutterView.getViewTreeObserver().removeOnPreDrawListener(this);
              activePreDrawListener = null;
            }
            return isFlutterUiDisplayed;
          }
        };
    flutterView.getViewTreeObserver().addOnPreDrawListener(activePreDrawListener);
  }

  /**
   * Invoke this from {@code Activity#onResume()} or {@code Fragment#onResume()}.
   *
   *
This method notifies the running Flutter app that it is "resumed" as per the Flutter app
   * lifecycle.
   */
  void onResume() {
    Log.v(TAG, "onResume()");
    ensureAlive();
    if (host.shouldDispatchAppLifecycleState()) {
      flutterEngine.getLifecycleChannel().appIsResumed();
    }
  }

  /**
   * Invoke this from {@code Activity#onPostResume()}.
   *
   *
A {@code Fragment} host must have its containing {@code Activity} forward this call so that
   * the {@code Fragment} can then invoke this method.
   *
   *
This method informs the {@link PlatformPlugin} that {@code onPostResume()} has run, which is
   * used to update system UI overlays.
   */
  // TODO(mattcarroll): determine why this can't be in onResume(). Comment reason, or move if
  // possible.
  void onPostResume() {
    Log.v(TAG, "onPostResume()");
    ensureAlive();
    if (flutterEngine != null) {
      updateSystemUiOverlays();
    } else {
      Log.w(TAG, "onPostResume() invoked before FlutterFragment was attached to an Activity.");
    }
  }

  /**
   * Refreshes Android's window system UI (AKA system chrome) to match Flutter's desired system
   * chrome style.
   */
  void updateSystemUiOverlays() {
    if (platformPlugin != null) {
      // TODO(mattcarroll): find a better way to handle the update of UI overlays than calling
      // through to platformPlugin. We're implicitly entangling the Window, Activity,
      // Fragment, and engine all with this one call.
      platformPlugin.updateSystemUiOverlays();
    }
  }

  /**
   * Invoke this from {@code Activity#onPause()} or {@code Fragment#onPause()}.
   *
   *
This method notifies the running Flutter app that it is "inactive" as per the Flutter app
   * lifecycle.
   */
  void onPause() {
    Log.v(TAG, "onPause()");
    ensureAlive();
    if (host.shouldDispatchAppLifecycleState()) {
      flutterEngine.getLifecycleChannel().appIsInactive();
    }
  }

  /**
   * Invoke this from {@code Activity#onStop()} or {@code Fragment#onStop()}.
   *
   *
This method:
   *
   *

   *
   *

   *
This method notifies the running Flutter app that it is "paused" as per the Flutter app
   *       lifecycle.
   *
Detaches this delegate's {@link io.flutter.embedding.engine.FlutterEngine} from this
   *       delegate's {@link FlutterView}.
   *

   */
  void onStop() {
    Log.v(TAG, "onStop()");
    ensureAlive();

    if (host.shouldDispatchAppLifecycleState()) {
      flutterEngine.getLifecycleChannel().appIsPaused();
    }

    // This is a workaround for a bug on some OnePlus phones. The visibility of the application
    // window is still true after locking the screen on some OnePlus phones, and shows a black
    // screen when unlocked. We can work around this by changing the visibility of FlutterView in
    // onStart and onStop.
    // See https://github.com/flutter/flutter/issues/93276
    previousVisibility = flutterView.getVisibility();
    flutterView.setVisibility(View.GONE);
  }

  /**
   * Invoke this from {@code Activity#onDestroy()} or {@code Fragment#onDestroyView()}.
   *
   *
This method removes this delegate's {@link FlutterView}'s {@link FlutterUiDisplayListener}.
   */
  void onDestroyView() {
    Log.v(TAG, "onDestroyView()");
    ensureAlive();

    if (activePreDrawListener != null) {
      flutterView.getViewTreeObserver().removeOnPreDrawListener(activePreDrawListener);
      activePreDrawListener = null;
    }
    flutterView.detachFromFlutterEngine();
    flutterView.removeOnFirstFrameRenderedListener(flutterUiDisplayListener);
  }

  void onSaveInstanceState(@Nullable Bundle bundle) {
    Log.v(TAG, "onSaveInstanceState. Giving framework and plugins an opportunity to save state.");
    ensureAlive();

    if (host.shouldRestoreAndSaveState()) {
      bundle.putByteArray(
          FRAMEWORK_RESTORATION_BUNDLE_KEY,
          flutterEngine.getRestorationChannel().getRestorationData());
    }

    if (host.shouldAttachEngineToActivity()) {
      final Bundle plugins = new Bundle();
      flutterEngine.getActivityControlSurface().onSaveInstanceState(plugins);
      bundle.putBundle(PLUGINS_RESTORATION_BUNDLE_KEY, plugins);
    }
  }

  @Override
  public void detachFromFlutterEngine() {
    if (host.shouldDestroyEngineWithHost()) {
      // The host owns the engine and should never have its engine taken by another exclusive
      // activity.
      throw new AssertionError(
          "The internal FlutterEngine created by "
              + host
              + " has been attached to by another activity. To persist a FlutterEngine beyond the "
              + "ownership of this activity, explicitly create a FlutterEngine");
    }

    // Default, but customizable, behavior is for the host to call {@link #onDetach}
    // deterministically as to not mix more events during the lifecycle of the next exclusive
    // activity.
    host.detachFromFlutterEngine();
  }

  /**
   * Invoke this from {@code Activity#onDestroy()} or {@code Fragment#onDetach()}.
   *
   *
This method:
   *
   *

   *
   *

   *
Detaches this delegate's {@link io.flutter.embedding.engine.FlutterEngine} from its
   *       surrounding {@code Activity}, if it was previously attached.
   *
Destroys this delegate's {@link PlatformPlugin}.
   *
Destroys this delegate's {@link io.flutter.embedding.engine.FlutterEngine} if {@link
   *       Host#shouldDestroyEngineWithHost()} ()} returns true.
   *

   */
  void onDetach() {
    Log.v(TAG, "onDetach()");
    ensureAlive();

    // Give the host an opportunity to cleanup any references that were created in
    // configureFlutterEngine().
    host.cleanUpFlutterEngine(flutterEngine);

    if (host.shouldAttachEngineToActivity()) {
      // Notify plugins that they are no longer attached to an Activity.
      Log.v(TAG, "Detaching FlutterEngine from the Activity that owns this Fragment.");
      if (host.getActivity().isChangingConfigurations()) {
        flutterEngine.getActivityControlSurface().detachFromActivityForConfigChanges();
      } else {
        flutterEngine.getActivityControlSurface().detachFromActivity();
      }
    }

    // Null out the platformPlugin to avoid a possible retain cycle between the plugin, this
    // Fragment,
    // and this Fragment's Activity.
    if (platformPlugin != null) {
      platformPlugin.destroy();
      platformPlugin = null;
    }

    if (host.shouldDispatchAppLifecycleState()) {
      flutterEngine.getLifecycleChannel().appIsDetached();
    }

    // Destroy our FlutterEngine if we're not set to retain it.
    if (host.shouldDestroyEngineWithHost()) {
      flutterEngine.destroy();

      if (host.getCachedEngineId() != null) {
        FlutterEngineCache.getInstance().remove(host.getCachedEngineId());
      }

      flutterEngine = null;
    }

    isAttached = false;
  }

  /**
   * Invoke this from {@link android.app.Activity#onBackPressed()}.
   *
   *
A {@code Fragment} host must have its containing {@code Activity} forward this call so that
   * the {@code Fragment} can then invoke this method.
   *
   *
This method instructs Flutter's navigation system to "pop route".
   */
  void onBackPressed() {
    ensureAlive();
    if (flutterEngine != null) {
      Log.v(TAG, "Forwarding onBackPressed() to FlutterEngine.");
      flutterEngine.getNavigationChannel().popRoute();
    } else {
      Log.w(TAG, "Invoked onBackPressed() before FlutterFragment was attached to an Activity.");
    }
  }

  /**
   * Invoke this from {@link android.app.Activity#onRequestPermissionsResult(int, String[], int[])}
   * or {@code Fragment#onRequestPermissionsResult(int, String[], int[])}.
   *
   *
This method forwards to interested Flutter plugins.
   */
  void onRequestPermissionsResult(
      int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    ensureAlive();
    if (flutterEngine != null) {
      Log.v(
          TAG,
          "Forwarding onRequestPermissionsResult() to FlutterEngine:\n"
              + "requestCode: "
              + requestCode
              + "\n"
              + "permissions: "
              + Arrays.toString(permissions)
              + "\n"
              + "grantResults: "
              + Arrays.toString(grantResults));
      flutterEngine
          .getActivityControlSurface()
          .onRequestPermissionsResult(requestCode, permissions, grantResults);
    } else {
      Log.w(
          TAG,
          "onRequestPermissionResult() invoked before FlutterFragment was attached to an Activity.");
    }
  }

  /**
   * Invoke this from {@code Activity#onNewIntent(Intent)}.
   *
   *
A {@code Fragment} host must have its containing {@code Activity} forward this call so that
   * the {@code Fragment} can then invoke this method.
   *
   *
This method forwards to interested Flutter plugins.
   */
  void onNewIntent(@NonNull Intent intent) {
    ensureAlive();
    if (flutterEngine != null) {
      Log.v(TAG, "Forwarding onNewIntent() to FlutterEngine and sending pushRoute message.");
      flutterEngine.getActivityControlSurface().onNewIntent(intent);
      String initialRoute = maybeGetInitialRouteFromIntent(intent);
      if (initialRoute != null && !initialRoute.isEmpty()) {
        flutterEngine.getNavigationChannel().pushRoute(initialRoute);
      }
    } else {
      Log.w(TAG, "onNewIntent() invoked before FlutterFragment was attached to an Activity.");
    }
  }

  /**
   * Invoke this from {@code Activity#onActivityResult(int, int, Intent)} or {@code
   * Fragment#onActivityResult(int, int, Intent)}.
   *
   *
This method forwards to interested Flutter plugins.
   */
  void onActivityResult(int requestCode, int resultCode, Intent data) {
    ensureAlive();
    if (flutterEngine != null) {
      Log.v(
          TAG,
          "Forwarding onActivityResult() to FlutterEngine:\n"
              + "requestCode: "
              + requestCode
              + "\n"
              + "resultCode: "
              + resultCode
              + "\n"
              + "data: "
              + data);
      flutterEngine.getActivityControlSurface().onActivityResult(requestCode, resultCode, data);
    } else {
      Log.w(TAG, "onActivityResult() invoked before FlutterFragment was attached to an Activity.");
    }
  }

  /**
   * Invoke this from {@code Activity#onUserLeaveHint()}.
   *
   *
A {@code Fragment} host must have its containing {@code Activity} forward this call so that
   * the {@code Fragment} can then invoke this method.
   *
   *
This method forwards to interested Flutter plugins.
   */
  void onUserLeaveHint() {
    ensureAlive();
    if (flutterEngine != null) {
      Log.v(TAG, "Forwarding onUserLeaveHint() to FlutterEngine.");
      flutterEngine.getActivityControlSurface().onUserLeaveHint();
    } else {
      Log.w(TAG, "onUserLeaveHint() invoked before FlutterFragment was attached to an Activity.");
    }
  }

  /**
   * Invoke this from {@link android.app.Activity#onTrimMemory(int)}.
   *
   *
A {@code Fragment} host must have its containing {@code Activity} forward this call so that
   * the {@code Fragment} can then invoke this method.
   *
   *
This method sends a "memory pressure warning" message to Flutter over the "system channel".
   */
  void onTrimMemory(int level) {
    ensureAlive();
    if (flutterEngine != null) {
      // Use a trim level delivered while the application is running so the
      // framework has a chance to react to the notification.
      // Avoid being too aggressive before the first frame is rendered. If it is
      // not at least running critical, we should avoid delaying the frame for
      // an overly aggressive GC.
      boolean trim = isFirstFrameRendered && level >= TRIM_MEMORY_RUNNING_LOW;
      if (trim) {
        flutterEngine.getDartExecutor().notifyLowMemoryWarning();
        flutterEngine.getSystemChannel().sendMemoryPressureWarning();
      }
      flutterEngine.getRenderer().onTrimMemory(level);
    }
  }

  /**
   * Ensures that this delegate has not been {@link #release()}'ed.
   *
   *
An {@code IllegalStateException} is thrown if this delegate has been {@link #release()}'ed.
   */
  private void ensureAlive() {
    if (host == null) {
      throw new IllegalStateException(
          "Cannot execute method on a destroyed FlutterActivityAndFragmentDelegate.");
    }
  }

  /**
   * The {@link FlutterActivity} or {@link FlutterFragment} that owns this {@code
   * FlutterActivityAndFragmentDelegate}.
   */
  /* package */ interface Host
      extends SplashScreenProvider,
          FlutterEngineProvider,
          FlutterEngineConfigurator,
          PlatformPlugin.PlatformPluginDelegate {
    /**
     * Returns the {@link Context} that backs the host {@link android.app.Activity} or {@code
     * Fragment}.
     */
    @NonNull
    Context getContext();

    /** Returns true if the delegate should retrieve the initial route from the {@link Intent}. */
    @Nullable
    boolean shouldHandleDeeplinking();

    /**
     * Returns the host {@link android.app.Activity} or the {@code Activity} that is currently
     * attached to the host {@code Fragment}.
     */
    @Nullable
    Activity getActivity();

    /**
     * Returns the {@link Lifecycle} that backs the host {@link android.app.Activity} or {@code
     * Fragment}.
     */
    @NonNull
    Lifecycle getLifecycle();

    /** Returns the {@link FlutterShellArgs} that should be used when initializing Flutter. */
    @NonNull
    FlutterShellArgs getFlutterShellArgs();

    /**
     * Returns the ID of a statically cached {@link io.flutter.embedding.engine.FlutterEngine} to
     * use within this delegate's host, or {@code null} if this delegate's host does not want to use
     * a cached {@link FlutterEngine}.
     */
    @Nullable
    String getCachedEngineId();

    /**
     * Returns true if the {@link io.flutter.embedding.engine.FlutterEngine} used in this delegate
     * should be destroyed when the host/delegate are destroyed.
     *
     *
The default value is {@code true} in cases where {@code FlutterFragment} created its own
     * {@link io.flutter.embedding.engine.FlutterEngine}, and {@code false} in cases where a cached
     * {@link io.flutter.embedding.engine.FlutterEngine} was provided.
     */
    boolean shouldDestroyEngineWithHost();

    /**
     * Callback called when the {@link io.flutter.embedding.engine.FlutterEngine} has been attached
     * to by another activity before this activity was destroyed.
     *
     *
The expected behavior is for this activity to synchronously stop using the {@link
     * FlutterEngine} to avoid lifecycle crosstalk with the new activity.
     */
    void detachFromFlutterEngine();

    /**
     * Returns the Dart entrypoint that should run when a new {@link
     * io.flutter.embedding.engine.FlutterEngine} is created.
     */
    @NonNull
    String getDartEntrypointFunctionName();

    /**
     * Returns the URI of the Dart library which contains the entrypoint method (example
     * "package:foo_package/main.dart"). If null, this will default to the same library as the
     * `main()` function in the Dart program.
     */
    @Nullable
    String getDartEntrypointLibraryUri();

    /** Returns arguments that passed as a list of string to Dart's entrypoint function. */
    @Nullable
    List<String> getDartEntrypointArgs();

    /** Returns the path to the app bundle where the Dart code exists. */
    @NonNull
    String getAppBundlePath();

    /** Returns the initial route that Flutter renders. */
    @Nullable
    String getInitialRoute();

    /**
     * Returns the {@link RenderMode} used by the {@link FlutterView} that displays the {@link
     * FlutterEngine}'s content.
     */
    @NonNull
    RenderMode getRenderMode();

    /**
     * Returns the {@link TransparencyMode} used by the {@link FlutterView} that displays the {@link
     * FlutterEngine}'s content.
     */
    @NonNull
    TransparencyMode getTransparencyMode();

    /**
     * Returns the {@link ExclusiveAppComponent<Activity>} that is associated with {@link
     * io.flutter.embedding.engine.FlutterEngine}.
     *
     *
In the scenario where multiple {@link FlutterActivity} or {@link FlutterFragment} share
     * the same {@link FlutterEngine}, to attach/re-attache a {@link FlutterActivity} or {@link
     * FlutterFragment} to the shared {@link FlutterEngine}, we MUST manually invoke {@link
     * ActivityControlSurface#attachToActivity(ExclusiveAppComponent, Lifecycle)}.
     *
     *
The {@link ExclusiveAppComponent} is exposed here so that subclasses of {@link
     * FlutterActivity} or {@link FlutterFragment} can access it.
     */
    ExclusiveAppComponent<Activity> getExclusiveAppComponent();

    @Nullable
    SplashScreen provideSplashScreen();

    /**
     * Returns the {@link io.flutter.embedding.engine.FlutterEngine} that should be rendered to a
     * {@link FlutterView}.
     *
     *
If {@code null} is returned, a new {@link io.flutter.embedding.engine.FlutterEngine} will
     * be created automatically.
     */
    @Nullable
    FlutterEngine provideFlutterEngine(@NonNull Context context);

    /**
     * Hook for the host to create/provide a {@link PlatformPlugin} if the associated Flutter
     * experience should control system chrome.
     */
    @Nullable
    PlatformPlugin providePlatformPlugin(
        @Nullable Activity activity, @NonNull FlutterEngine flutterEngine);

    /**
     * Hook for the host to configure the {@link io.flutter.embedding.engine.FlutterEngine} as
     * desired.
     */
    void configureFlutterEngine(@NonNull FlutterEngine flutterEngine);

    /**
     * Hook for the host to cleanup references that were established in {@link
     * #configureFlutterEngine(FlutterEngine)} before the host is destroyed or detached.
     */
    void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine);

    /**
     * Returns true if the {@link io.flutter.embedding.engine.FlutterEngine}'s plugin system should
     * be connected to the host {@link android.app.Activity}, allowing plugins to interact with it.
     */
    boolean shouldAttachEngineToActivity();

    /**
     * Invoked by this delegate when the {@link FlutterSurfaceView} that renders the Flutter UI is
     * initially instantiated.
     *
     *
This method is only invoked if the {@link
     * io.flutter.embedding.android.FlutterView.RenderMode} is set to {@link
     * io.flutter.embedding.android.FlutterView.RenderMode#surface}. Otherwise, {@link
     * #onFlutterTextureViewCreated(FlutterTextureView)} is invoked.
     *
     *
This method is invoked before the given {@link FlutterSurfaceView} is attached to the
     * {@code View} hierarchy. Implementers should not attempt to climb the {@code View} hierarchy
     * or make assumptions about relationships with other {@code View}s.
     */
    void onFlutterSurfaceViewCreated(@NonNull FlutterSurfaceView flutterSurfaceView);

    /**
     * Invoked by this delegate when the {@link FlutterTextureView} that renders the Flutter UI is
     * initially instantiated.
     *
     *
This method is only invoked if the {@link
     * io.flutter.embedding.android.FlutterView.RenderMode} is set to {@link
     * io.flutter.embedding.android.FlutterView.RenderMode#texture}. Otherwise, {@link
     * #onFlutterSurfaceViewCreated(FlutterSurfaceView)} is invoked.
     *
     *
This method is invoked before the given {@link FlutterTextureView} is attached to the
     * {@code View} hierarchy. Implementers should not attempt to climb the {@code View} hierarchy
     * or make assumptions about relationships with other {@code View}s.
     */
    void onFlutterTextureViewCreated(@NonNull FlutterTextureView flutterTextureView);

    /** Invoked by this delegate when its {@link FlutterView} starts painting pixels. */
    void onFlutterUiDisplayed();

    /** Invoked by this delegate when its {@link FlutterView} stops painting pixels. */
    void onFlutterUiNoLongerDisplayed();

    /**
     * Whether state restoration is enabled.
     *
     *
When this returns true, the instance state provided to {@code
     * onRestoreInstanceState(Bundle)} will be forwarded to the framework via the {@code
     * RestorationChannel} and during {@code onSaveInstanceState(Bundle)} the current framework
     * instance state obtained from {@code RestorationChannel} will be stored in the provided
     * bundle.
     *
     *
This defaults to true, unless a cached engine is used.
     */
    boolean shouldRestoreAndSaveState();

    /**
     * Refreshes Android's window system UI (AKA system chrome) to match Flutter's desired system
     * chrome style.
     *
     *
This is useful when using the splash screen API available in Android 12. {@code
     * SplashScreenView#remove} resets the system UI colors to the values set prior to the execution
     * of the Dart entrypoint. As a result, the values set from Dart are reverted by this API. To
     * workaround this issue, call this method after removing the splash screen with {@code
     * SplashScreenView#remove}.
     */
    void updateSystemUiOverlays();

    /**
     * Give the host application a chance to take control of the app lifecycle events to avoid
     * lifecycle crosstalk.
     *
     *
In the add-to-app scenario where multiple {@link FlutterActivity} shares the same {@link
     * FlutterEngine}, the application lifecycle state will have crosstalk causing the page to
     * freeze. For example, we open a new page called FlutterActivity#2 from the previous page
     * called FlutterActivity#1. The flow of app lifecycle states received by dart is as follows:
     *
     *
inactive (from FlutterActivity#1) -> resumed (from FlutterActivity#2) -> paused (from
     * FlutterActivity#1)
     *
     *
On the one hand, the {@code paused} state from FlutterActivity#1 will cause the
     * FlutterActivity#2 page to be stuck; On the other hand, these states are not expected from the
     * perspective of the entire application lifecycle. If the host application gets the control of
     * sending {@link AppLifecycleState}, It will be possible to correctly match the {@link
     * AppLifecycleState} with the application-level lifecycle.
     *
     *
Return {@code false} means the host application dispatches these app lifecycle events,
     * while return {@code true} means the engine dispatches these events.
     */
    boolean shouldDispatchAppLifecycleState();
  }
}


text:
<?php

namespace DeliciousBrains\WP_Offload_Media\Aws3\Aws\Exception;

use DeliciousBrains\WP_Offload_Media\Aws3\Aws\HasMonitoringEventsTrait;
use DeliciousBrains\WP_Offload_Media\Aws3\Aws\MonitoringEventsInterface;
class CredentialsException extends \RuntimeException implements \DeliciousBrains\WP_Offload_Media\Aws3\Aws\MonitoringEventsInterface
{
    use HasMonitoringEventsTrait;
}

redpajama_set_name: RedPajamaGithub


text:
namespace Corlib.Configuration {
    public class TriggerConfig {

        public string TriggerFile { get; set; }

        public ProcessAction ProcessAction { get; set; }

        public TriggerType GetTriggerType () {
            if (!string.IsNullOrWhiteSpace (TriggerFile))
                return TriggerType.File;

            return TriggerType.Undefined;
        }

        public ActionType GetActionType () {
            if (null != ProcessAction)
                return ActionType.Process;

            return ActionType.Undefined;
        }
    }
}


text:
// @file dur.h durability support

#pragma once

#include <boost/filesystem/operations.hpp>
#include <list>

#include "mongo/db/dur_journalformat.h"
#include "mongo/util/concurrency/mutex.h"
#include "mongo/util/file.h"

namespace mongo {
    class MongoMMF;

    namespace dur {
        struct ParsedJournalEntry;

        /** call go() to execute a recovery from existing journal files.
         */
        class RecoveryJob : boost::noncopyable {
            static class Last {
            public:
                Last();
                MongoMMF* newEntry(const ParsedJournalEntry&, RecoveryJob&);
            private:
                MongoMMF *mmf;
                string dbName;
                int fileNo;
            } last;
        public:
            RecoveryJob() : _lastDataSyncedFromLastRun(0),
                _mx("recovery"), _recovering(false) { _lastSeqMentionedInConsoleLog = 1; }
            void go(vector<boost::filesystem::path>& files);
            ~RecoveryJob();

            /** @param data data between header and footer. compressed if recovering. */
            void processSection(const JSectHeader *h, const void *data, unsigned len, const JSectFooter *f);

            void close(); // locks and calls _close()

            static RecoveryJob & get() { return _instance; }
        private:
            void write(Last& last, const ParsedJournalEntry& entry); // actually writes to the file
            void applyEntry(Last& last, const ParsedJournalEntry& entry, bool apply, bool dump);
            void applyEntries(const vector<ParsedJournalEntry> &entries);
            bool processFileBuffer(const void *, unsigned len);
            bool processFile(boost::filesystem::path journalfile);
            void _close(); // doesn't lock
            MongoMMF* getMongoMMF(const ParsedJournalEntry& entry);

            list<boost::shared_ptr<MongoMMF> > _mmfs;

            unsigned long long _lastDataSyncedFromLastRun;
            unsigned long long _lastSeqMentionedInConsoleLog;
        public:
            mongo::mutex _mx; // protects _mmfs
        private:
            bool _recovering; // are we in recovery or WRITETODATAFILES

            static RecoveryJob &_instance;
        };
    }
}


text:
import Joi from "joi"

export default class Validator {
    constructor(schema) {

        this.schema = schema
        this._errors = {}
        this._valid = false
    }

    get errors() {
        return this._errors
    }

    get isValid() {
        return this._valid
    }

    validate(value, cb) {
        this._valid = true
        this._errors = {}

        Joi.validate(value, this.schema, {abortEarly: false}, (error) => {
            if(!error) {
                return
            }
            this._valid = false
            for(let detail of error.details) {
                this._errors[detail.path] = {
                    message: detail.message
                }
            }

            if(cb) cb()
        })
    }

    validateField(field, value) {
        let subSchema = Joi.reach(this.schema, field)

        try{
            Joi.assert(value, subSchema)
            if(this._errors[field]) delete this._errors[field]
        } catch(error) {
            if(!this._errors[field]) this._errors[field] = {}

            for(let detail of error.details) {
                this._errors[field] = {
                    message: detail.message
                }
            }
        }
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Value types of an Option.
 */
var OptionType;
(function (OptionType) {
    OptionType["Any"] = "any";
    OptionType["Array"] = "array";
    OptionType["Boolean"] = "boolean";
    OptionType["Number"] = "number";
    OptionType["String"] = "string";
})(OptionType = exports.OptionType || (exports.OptionType = {}));
/**
 * Scope of the command.
 */
var CommandScope;
(function (CommandScope) {
    CommandScope["InProject"] = "in";
    CommandScope["OutProject"] = "out";
    CommandScope["Everywhere"] = "all";
    CommandScope["Default"] = "in";
})(CommandScope = exports.CommandScope || (exports.CommandScope = {}));


text:
import unittest
import re

from VintageousEx.test_runner import g_test_view
from VintageousEx.tests import select_bof
from VintageousEx.tests import select_eof
from VintageousEx.tests import select_line

from VintageousEx.vex.ex_range import EX_RANGE
from VintageousEx.vex.ex_range import new_calculate_range
from VintageousEx.vex.ex_range import calculate_relative_ref
from VintageousEx.vex.ex_range import calculate_address

class TestCalculateRelativeRef(unittest.TestCase):
    def StartUp(self):
        select_bof(g_test_view)

    def tearDown(self):
        select_bof(g_test_view)

    def testCalculateRelativeRef(self):
        values = (
            (calculate_relative_ref(g_test_view, '.'), 1),
            (calculate_relative_ref(g_test_view, '.', start_line=100), 101),
            (calculate_relative_ref(g_test_view, '$'), 538),
            (calculate_relative_ref(g_test_view, '$', start_line=100), 538),
        )

        for actual, expected in values:
            self.assertEquals(actual, expected)

    def testCalculateRelativeRef2(self):
        self.assertEquals(calculate_relative_ref(g_test_view, '.'), 1)
        self.assertEquals(calculate_relative_ref(g_test_view, '$'), 538)

        select_line(g_test_view, 100)
        self.assertEquals(calculate_relative_ref(g_test_view, '.'), 100)

        select_line(g_test_view, 200)
        self.assertEquals(calculate_relative_ref(g_test_view, '.'), 200)

class TestCalculatingRanges(unittest.TestCase):
    def testCalculateCorrectRange(self):
        values = (
            (new_calculate_range(g_test_view, '0'), [(0, 0)]),
            (new_calculate_range(g_test_view, '1'), [(1, 1)]),
            (new_calculate_range(g_test_view, '1,1'), [(1, 1)]),
            (new_calculate_range(g_test_view, '%,1'), [(1, 538)]),
            (new_calculate_range(g_test_view, '1,%'), [(1, 538)]),
            (new_calculate_range(g_test_view, '1+99,160-10'), [(100, 150)]),
            (new_calculate_range(g_test_view, '/THIRTY/+10,100'), [(40, 100)]),
        )

        select_line(g_test_view, 31)
        values += (
            (new_calculate_range(g_test_view, '10,/THIRTY/'), [(10, 31)]),
            (new_calculate_range(g_test_view, '10;/THIRTY/'), [(10, 30)]),
        )

        for actual, expected in values:
            self.assertEquals(actual, expected)

    def tearDown(self):
        select_bof(g_test_view)

class CalculateAddress(unittest.TestCase):
    def setUp(self):
        select_eof(g_test_view)

    def tearDown(self):
        select_bof(g_test_view)

    def testCalculateAddressCorrectly(self):
        values = (
            (dict(ref='100', offset=None, search_offsets=[]), 99),
            (dict(ref='200', offset=None, search_offsets=[]), 199),
        )

        for v, expected in values:
            self.assertEquals(calculate_address(g_test_view, v), expected)

    def testOutOfBoundsAddressShouldReturnNone(self):
        address = dict(ref='1000', offset=None, search_offsets=[])
        self.assertEquals(calculate_address(g_test_view, address), None)

    def testInvalidAddressShouldReturnNone(self):
        address = dict(ref='XXX', offset=None, search_offsets=[])
        self.assertRaises(AttributeError, calculate_address, g_test_view, address)


text:
namespace pidl
{
namespace ast
{
class AttributeValue;
class AttributeList: public pidl::ast::Statement
{
public:
	AttributeList();
	virtual ~AttributeList() = default;

	void appendChild(std::unique_ptr<AttributeValue> child);

	virtual void output(std::ostream& stream) const override;

protected:
};

}
}

#endif


text:
/*
 * 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 com.facebook.presto.hive;

import com.facebook.presto.rcfile.AircompressorCodecFactory;
import com.facebook.presto.rcfile.HadoopCodecFactory;
import com.facebook.presto.rcfile.RcFileDataSource;
import com.facebook.presto.rcfile.RcFileEncoding;
import com.facebook.presto.rcfile.RcFileWriter;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.RunLengthEncodedBlock;
import com.facebook.presto.spi.type.Type;
import com.google.common.collect.ImmutableList;
import com.google.common.io.CountingOutputStream;
import io.airlift.slice.OutputStreamSliceOutput;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Supplier;

import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_CLOSE_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_DATA_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITE_VALIDATION_FAILED;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;

public class RcFileFileWriter
        implements HiveFileWriter
{
    private final CountingOutputStream outputStream;
    private final RcFileWriter rcFileWriter;
    private final Callable<Void> rollbackAction;
    private final int[] fileInputColumnIndexes;
    private final List<Block> nullBlocks;
    private final Optional<Supplier<RcFileDataSource>> validationInputFactory;

    public RcFileFileWriter(
            OutputStream outputStream,
            Callable<Void> rollbackAction,
            RcFileEncoding rcFileEncoding,
            List<Type> fileColumnTypes,
            Optional<String> codecName,
            int[] fileInputColumnIndexes,
            Map<String, String> metadata,
            Optional<Supplier<RcFileDataSource>> validationInputFactory)
            throws IOException
    {
        this.outputStream = new CountingOutputStream(outputStream);
        rcFileWriter = new RcFileWriter(
                new OutputStreamSliceOutput(this.outputStream),
                fileColumnTypes,
                rcFileEncoding,
                codecName,
                new AircompressorCodecFactory(new HadoopCodecFactory(getClass().getClassLoader())),
                metadata,
                validationInputFactory.isPresent());
        this.rollbackAction = requireNonNull(rollbackAction, "rollbackAction is null");

        this.fileInputColumnIndexes = requireNonNull(fileInputColumnIndexes, "outputColumnInputIndexes is null");

        ImmutableList.Builder<Block> nullBlocks = ImmutableList.builder();
        for (Type fileColumnType : fileColumnTypes) {
            BlockBuilder blockBuilder = fileColumnType.createBlockBuilder(null, 1, 0);
            blockBuilder.appendNull();
            nullBlocks.add(blockBuilder.build());
        }
        this.nullBlocks = nullBlocks.build();
        this.validationInputFactory = validationInputFactory;
    }

    @Override
    public long getWrittenBytes()
    {
        return outputStream.getCount();
    }

    @Override
    public long getSystemMemoryUsage()
    {
        return rcFileWriter.getRetainedSizeInBytes();
    }

    @Override
    public void appendRows(Page dataPage)
    {
        Block[] blocks = new Block[fileInputColumnIndexes.length];
        for (int i = 0; i < fileInputColumnIndexes.length; i++) {
            int inputColumnIndex = fileInputColumnIndexes[i];
            if (inputColumnIndex < 0) {
                blocks[i] = new RunLengthEncodedBlock(nullBlocks.get(i), dataPage.getPositionCount());
            }
            else {
                blocks[i] = dataPage.getBlock(inputColumnIndex);
            }
        }
        Page page = new Page(dataPage.getPositionCount(), blocks);
        try {
            rcFileWriter.write(page);
        }
        catch (IOException | UncheckedIOException e) {
            throw new PrestoException(HIVE_WRITER_DATA_ERROR, e);
        }
    }

    @Override
    public void commit()
    {
        try {
            rcFileWriter.close();
        }
        catch (IOException | UncheckedIOException e) {
            try {
                rollbackAction.call();
            }
            catch (Exception ignored) {
                // ignore
            }
            throw new PrestoException(HIVE_WRITER_CLOSE_ERROR, "Error committing write to Hive", e);
        }

        if (validationInputFactory.isPresent()) {
            try {
                try (RcFileDataSource input = validationInputFactory.get().get()) {
                    rcFileWriter.validate(input);
                }
            }
            catch (IOException | UncheckedIOException e) {
                throw new PrestoException(HIVE_WRITE_VALIDATION_FAILED, e);
            }
        }
    }

    @Override
    public void rollback()
    {
        try {
            try {
                rcFileWriter.close();
            }
            finally {
                rollbackAction.call();
            }
        }
        catch (Exception e) {
            throw new PrestoException(HIVE_WRITER_CLOSE_ERROR, "Error rolling back write to Hive", e);
        }
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .add("writer", rcFileWriter)
                .toString();
    }
}


text:
using System;
using System.IO;
using GroupDocs.Conversion.Options.Convert;

namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage
{
    /// <summary>
    /// This example demonstrates how to convert DOTM file into HTML format.
    /// For more details about Microsoft Word Macro-Enabled Template (.dotm) to Hyper Text Markup Language (.html) conversion please check this documentation article
    /// https://docs.groupdocs.com/conversion/net/convert-dotm-to-html
    /// </summary>
    internal static class ConvertDotmToHtml
    {
        public static void Run()
        {
            string outputFolder = Constants.GetOutputDirectoryPath();
            string outputFile = Path.Combine(outputFolder, "dotm-converted-to.html");

            // Load the source DOTM file
            using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_DOTM))
            {
                var options = new MarkupConvertOptions();
                // Save converted HTML file
                converter.Convert(outputFile, options);
            }

            Console.WriteLine("\nConversion to html completed successfully. \nCheck output in {0}", outputFolder);
        }
    }
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef nsIHTMLDocument_h___
#define nsIHTMLDocument_h___

#include "nsISupports.h"
#include "nsCompatibility.h"
#include "nsContentList.h"

class nsIImageMap;
class nsString;
class nsIDOMNodeList;
class nsIDOMHTMLCollection;
class nsIDOMHTMLFormElement;
class nsIDOMHTMLMapElement;
class nsHTMLStyleSheet;
class nsIStyleSheet;
class nsICSSLoader;
class nsIContent;
class nsIDOMHTMLBodyElement;
class nsIScriptElement;
class nsIEditor;

// 19d63a6c-cc94-499c-892a-955add772e10
#define NS_IHTMLDOCUMENT_IID \
{ 0x19d63a6c, 0xcc94, 0x499c, \
  { 0x89, 0x2a, 0x95, 0x5a, 0xdd, 0x77, 0x2e, 0x10 } }

/**
 * HTML document extensions to nsIDocument.
 */
class nsIHTMLDocument : public nsISupports
{
public:
  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IHTMLDOCUMENT_IID)

  virtual nsresult AddImageMap(nsIDOMHTMLMapElement* aMap) = 0;

  virtual nsIDOMHTMLMapElement *GetImageMap(const nsAString& aMapName) = 0;

  virtual void RemoveImageMap(nsIDOMHTMLMapElement* aMap) = 0;

  /**
   * Set compatibility mode for this document
   */
  virtual void SetCompatibilityMode(nsCompatibility aMode) = 0;

  virtual nsresult ResolveName(const nsAString& aName,
                               nsIDOMHTMLFormElement *aForm,
                               nsISupports **aResult) = 0;

  /**
   * Called from the script loader to notify this document that a new
   * script is being loaded.
   */
  virtual void ScriptLoading(nsIScriptElement *aScript) = 0;

  /**
   * Called from the script loader to notify this document that a script
   * just finished executing.
   */
  virtual void ScriptExecuted(nsIScriptElement *aScript) = 0;

  /**
   * Called when form->BindToTree() is called so that document knows
   * immediately when a form is added
   */
  virtual void AddedForm() = 0;
  /**
   * Called when form->SetDocument() is called so that document knows
   * immediately when a form is removed
   */
  virtual void RemovedForm() = 0;
  /**
   * Called to get a better count of forms than document.forms can provide
   * without calling FlushPendingNotifications (bug 138892).
   */
  // XXXbz is this still needed now that we can flush just content,
  // not the rest?
  virtual PRInt32 GetNumFormsSynchronous() = 0;

  virtual PRBool IsWriting() = 0;

  virtual PRBool GetIsFrameset() = 0;
  virtual void SetIsFrameset(PRBool aFrameset) = 0;

  /**
   * Get the list of form elements in the document.
   */
  virtual nsContentList* GetForms() = 0;

  /**
   * Get the list of form controls in the document (all elements in
   * the document that are of type nsIContent::eHTML_FORM_CONTROL).
   */
  virtual nsContentList* GetFormControls() = 0;

  /**
   * Should be called when an element's editable changes as a result of
   * changing its contentEditable attribute/property.
   *
   * @param aElement the element for which the contentEditable
   *                 attribute/property was changed
   * @param aChange +1 if the contentEditable attribute/property was changed to
   *                true, -1 if it was changed to false
   */
  virtual nsresult ChangeContentEditableCount(nsIContent *aElement,
                                              PRInt32 aChange) = 0;

  enum EditingState {
    eTearingDown = -2,
    eSettingUp = -1,
    eOff = 0,
    eDesignMode,
    eContentEditable
  };

  /**
   * Returns whether the document is editable.
   */
  PRBool IsEditingOn()
  {
    return GetEditingState() == eDesignMode ||
           GetEditingState() == eContentEditable;
  }

  /**
   * Returns the editing state of the document (not editable, contentEditable or
   * designMode).
   */
  virtual EditingState GetEditingState() = 0;

  /**
   * Set the editing state of the document. Don't use this if you want
   * to enable/disable editing, call EditingStateChanged() or
   * SetDesignMode().
   */
  virtual nsresult SetEditingState(EditingState aState) = 0;

  /**
   * Returns the result of document.all[aID] which can either be a node
   * or a nodelist depending on if there are multiple nodes with the same
   * id.
   */
  virtual nsresult GetDocumentAllResult(const nsAString& aID,
                                        nsISupports** aResult) = 0;

  /**
   * Get the first <body> child of the root <html>, but don't do
   * anything <frameset>-related (like nsIDOMHTMLDocument::GetBody).
   */
  virtual nsIContent* GetBodyContentExternal() = 0;

  /**
   * Called when this nsIHTMLDocument's editor is destroyed.
   */
  virtual void TearingDownEditor(nsIEditor *aEditor) = 0;
};

NS_DEFINE_STATIC_IID_ACCESSOR(nsIHTMLDocument, NS_IHTMLDOCUMENT_IID)

#endif /* nsIHTMLDocument_h___ */