{
17 |
18 | @Inject
19 | PhotoDisplayScreen.Presenter presenter;
20 |
21 | @InjectView(R.id.photo_display_image)
22 | ImageView photoDisplayImage;
23 |
24 | public PhotoDisplayView(Context context, AttributeSet attrs) {
25 | super(context, attrs);
26 | }
27 |
28 | @Override
29 | public PhotoDisplayScreen.Presenter getPresenter() {
30 | return presenter;
31 | }
32 |
33 | @OnClick(R.id.photo_display_pick_button)
34 | public void photoDisplayPickButtonClicked() {
35 | presenter.handlePhotoDisplayPickButtonClicked();
36 | }
37 |
38 | public void setImage(Bitmap selectedImage) {
39 | photoDisplayImage.setImageBitmap(selectedImage);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/main_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
21 |
22 |
23 |
29 |
30 |
36 |
37 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/dagger/Blueprint.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.common.dagger;
2 |
3 | /**
4 | * Defines a scope to be built via {@link ObjectGraphService#requireChild(mortar.MortarScope, Blueprint)}
5 | * or {@link ObjectGraphService#requireActivityScope(mortar.MortarScope, Blueprint)}.
6 | *
7 | * @deprecated see deprecation note on {@link ObjectGraphService#requireChild(mortar.MortarScope,
8 | * Blueprint)}
9 | */
10 | @Deprecated public interface Blueprint {
11 | /**
12 | * Returns the name of the new scope. This can be used later to {@link
13 | * mortar.MortarScope#findChild(String) find} it in its parent. If {@link
14 | * ObjectGraphService#requireChild(mortar.MortarScope, Blueprint)} is called again with a {@link
15 | * Blueprint} of the same name, the original instance will be returned unless it has been
16 | * {@link mortar.MortarScope#destroy} destroyed}.
17 | */
18 | String getMortarScopeName();
19 |
20 | /**
21 | * Returns the {@literal @}{@link dagger.Module Module} that will define the scope
22 | * of the new graph by being added to that of its parent. If the returned value
23 | * is an instance of {@link java.util.Collection} its contents will be used as modules.
24 | * Returns null if this scope needs no modules.
25 | *
26 | * @see dagger.ObjectGraph#plus(Object...)
27 | */
28 | Object getDaggerModule();
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/flow/Layout.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package co.moonmonkeylabs.flowmortarexampleapp.common.flow;
18 |
19 | import java.lang.annotation.Retention;
20 | import java.lang.annotation.Target;
21 |
22 | import static java.lang.annotation.ElementType.TYPE;
23 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
24 |
25 | /**
26 | * Marks a class that designates a screen and specifies its layout. A screen is a distinct part of
27 | * an application containing all information that describes this state.
28 | *
29 | * For example,
30 | * {@literal@}Layout(R.layout.conversation_screen_layout)
31 | * public class ConversationScreen { ... }
32 | *
33 | */
34 | @Retention(RUNTIME) @Target(TYPE) public @interface Layout {
35 | int value();
36 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/flowmortar/MortarScreenSwitcherFrame.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package co.moonmonkeylabs.flowmortarexampleapp.common.flowmortar;
17 |
18 | import android.content.Context;
19 | import android.util.AttributeSet;
20 |
21 |
22 | import co.moonmonkeylabs.flowmortarexampleapp.R;
23 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.FramePathContainerView;
24 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.SimplePathContainer;
25 | import flow.path.Path;
26 |
27 | public class MortarScreenSwitcherFrame extends FramePathContainerView {
28 | public MortarScreenSwitcherFrame(Context context, AttributeSet attrs) {
29 | super(context, attrs, new SimplePathContainer(R.id.screen_switcher_tag,
30 | Path.contextFactory(new MortarContextFactory())));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/flow/HandlesBack.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package co.moonmonkeylabs.flowmortarexampleapp.common.flow;
18 |
19 | /**
20 | * Implemented by views that want the option to intercept back button taps. If a view has subviews
21 | * that implement this interface their {@link #onBackPressed()} method should be invoked before
22 | * any of this view's own logic.
23 | *
24 | *
25 | * The typical flow of back button handling starts in the {@link android.app.Activity#onBackPressed()}
26 | * calling {@link #onBackPressed()} on its content view. Each view in turn delegates to its
27 | * child views to give them first say.
28 | */
29 | public interface HandlesBack {
30 | /**
31 | * Returns true if back event was handled, false if someone higher in
32 | * the chain should.
33 | */
34 | boolean onBackPressed();
35 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/FlowMortarExampleApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package co.moonmonkeylabs.flowmortarexampleapp;
17 |
18 | import android.app.Application;
19 |
20 | import co.moonmonkeylabs.flowmortarexampleapp.common.dagger.ObjectGraphService;
21 | import dagger.ObjectGraph;
22 | import mortar.MortarScope;
23 |
24 | public class FlowMortarExampleApplication extends Application {
25 | private MortarScope rootScope;
26 |
27 | @Override public Object getSystemService(String name) {
28 | if (rootScope == null) {
29 | rootScope = MortarScope.buildRootScope()
30 | .withService(
31 | ObjectGraphService.SERVICE_NAME,
32 | ObjectGraph.create(new ApplicationModule(this)))
33 | .build("Root");
34 | }
35 |
36 | if (rootScope.hasService(name)) return rootScope.getService(name);
37 |
38 | return super.getSystemService(name);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/view/Wizard1View.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.view;
2 |
3 | import android.content.Context;
4 | import android.util.AttributeSet;
5 | import android.widget.TextView;
6 |
7 | import javax.inject.Inject;
8 |
9 | import butterknife.InjectView;
10 | import butterknife.OnClick;
11 | import co.moonmonkeylabs.flowmortarexampleapp.R;
12 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.BackSupport;
13 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.HandlesBack;
14 | import co.moonmonkeylabs.flowmortarexampleapp.common.widget.CustomLinearLayout;
15 | import co.moonmonkeylabs.flowmortarexampleapp.screen.Wizard1Screen;
16 |
17 | public class Wizard1View extends CustomLinearLayout implements HandlesBack {
18 |
19 | @Inject
20 | Wizard1Screen.Presenter presenter;
21 |
22 | @InjectView(R.id.wizard_1_count)
23 | TextView wizardCounter;
24 |
25 | public Wizard1View(Context context, AttributeSet attrs) {
26 | super(context, attrs);
27 | }
28 |
29 | @Override
30 | public Wizard1Screen.Presenter getPresenter() {
31 | return presenter;
32 | }
33 |
34 | @OnClick(R.id.wizard_1_next_button)
35 | public void nextButtonClicked() {
36 | presenter.handleNextButtonClicked();
37 | }
38 |
39 | public void updateWizardCount(int count) {
40 | wizardCounter.setText("Wizard Step Counter: " + count);
41 | }
42 |
43 | @Override
44 | public boolean onBackPressed() {
45 | presenter.handleBackPressed();
46 | return false;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/screen/RotationScreen.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.screen;
2 |
3 | import android.os.Bundle;
4 |
5 | import javax.inject.Inject;
6 | import javax.inject.Singleton;
7 |
8 | import co.moonmonkeylabs.flowmortarexampleapp.ActivityModule;
9 | import co.moonmonkeylabs.flowmortarexampleapp.R;
10 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.Layout;
11 | import co.moonmonkeylabs.flowmortarexampleapp.common.mortarscreen.WithModule;
12 | import co.moonmonkeylabs.flowmortarexampleapp.view.RotationView;
13 | import flow.path.Path;
14 | import mortar.ViewPresenter;
15 |
16 | @Layout(R.layout.rotation_layout)
17 | @WithModule(RotationScreen.Module.class)
18 | public class RotationScreen extends Path {
19 |
20 | @dagger.Module(injects = RotationView.class, addsTo = ActivityModule.class)
21 | public class Module {
22 | }
23 |
24 | @Singleton
25 | public static class Presenter extends ViewPresenter {
26 |
27 | private int onLoadCount = 0;
28 |
29 | @Inject
30 | public Presenter() {
31 | }
32 |
33 | @Override
34 | protected void onLoad(Bundle savedInstanceState) {
35 | super.onLoad(savedInstanceState);
36 |
37 | if (onLoadCount == 0 && savedInstanceState != null) {
38 | onLoadCount = savedInstanceState.getInt("onLoadCount", 0);
39 | }
40 |
41 | getView().updateCount(++onLoadCount);
42 | }
43 |
44 |
45 | @Override
46 | protected void onSave(Bundle outState) {
47 | outState.putInt("onLoadCount", onLoadCount);
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/lifecycle/LifecycleViewPresenter.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.common.lifecycle;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import android.view.View;
6 |
7 | import mortar.ViewPresenter;
8 |
9 | /**
10 | * ViewPresenter that gets lifecycle events.
11 | */
12 | public class LifecycleViewPresenter
13 | extends ViewPresenter
14 | implements ActivityLifecycleListener {
15 |
16 | protected final LifecycleOwner lifecycleOwner;
17 |
18 | public LifecycleViewPresenter(LifecycleOwner lifecycleOwner) {
19 | this.lifecycleOwner = lifecycleOwner;
20 | }
21 |
22 | @Override
23 | protected void onLoad(Bundle savedInstanceState) {
24 | super.onLoad(savedInstanceState);
25 | lifecycleOwner.register(this);
26 | onActivityResume();
27 | }
28 |
29 | @Override
30 | public void dropView(V view) {
31 | onActivityPause();
32 | super.dropView(view);
33 | }
34 |
35 | @Override
36 | protected void onExitScope() {
37 | super.onExitScope();
38 | lifecycleOwner.unregister(this);
39 | }
40 |
41 | @Override
42 | public void onActivityResume() {
43 | }
44 |
45 | @Override
46 | public void onActivityPause() {
47 | }
48 |
49 | @Override
50 | public void onActivityStart() {
51 | }
52 |
53 | @Override
54 | public void onActivityStop() {
55 | }
56 |
57 | @Override
58 | public void onLowMemory() {
59 | }
60 |
61 | @Override
62 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/view/MainView.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.view;
2 |
3 | import android.content.Context;
4 | import android.util.AttributeSet;
5 | import android.widget.TextView;
6 |
7 | import javax.inject.Inject;
8 |
9 | import butterknife.OnClick;
10 | import co.moonmonkeylabs.flowmortarexampleapp.R;
11 | import co.moonmonkeylabs.flowmortarexampleapp.common.widget.CustomLinearLayout;
12 | import co.moonmonkeylabs.flowmortarexampleapp.screen.MainScreen;
13 |
14 | public class MainView extends CustomLinearLayout {
15 |
16 | @Inject
17 | MainScreen.Presenter presenter;
18 |
19 | public MainView(Context context, AttributeSet attrs) {
20 | super(context, attrs);
21 | }
22 |
23 | @Override
24 | public MainScreen.Presenter getPresenter() {
25 | return presenter;
26 | }
27 |
28 | @Override
29 | protected void onAttachedToWindow() {
30 | super.onAttachedToWindow();
31 | }
32 |
33 | @OnClick(R.id.main_buttons_rotation_screen)
34 | public void rotationScreenButtonClicked() {
35 | presenter.handleRotationScreenButtonClicked();
36 | }
37 |
38 | @OnClick(R.id.main_buttons_photo_display_screen)
39 | public void photoDisplayScreenButtonClicked() {
40 | presenter.handlePhotoDisplayScreenButtonClicked();
41 | }
42 |
43 | @OnClick(R.id.main_buttons_settings_screen)
44 | public void settingsScreenButtonClicked() {
45 | presenter.handleSettingsScreenButtonClicked();
46 | }
47 |
48 | @OnClick(R.id.main_buttons_wizard_screen)
49 | public void wizardScreenButtonClicked() {
50 | presenter.handleWizardScreenButtonClicked();
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/setting/SettingsModule.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package co.moonmonkeylabs.flowmortarexampleapp.setting;
17 |
18 | import android.app.Application;
19 | import android.content.Context;
20 | import android.content.SharedPreferences;
21 |
22 | import co.moonmonkeylabs.flowmortarexampleapp.common.setting.StringLocalSetting;
23 | import dagger.Module;
24 | import dagger.Provides;
25 |
26 | /**
27 | * Defines app-wide singletons.
28 | */
29 | @Module(
30 | library = true,
31 | complete = false
32 | )
33 | public class SettingsModule {
34 |
35 | private static final String PREFERENCES_NAME = "mortar_flow_example_preferences";
36 |
37 | @Provides
38 | public SharedPreferences providesSharedPreferences(Application application) {
39 | return application.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
40 | }
41 |
42 |
43 | @Provides
44 | @UserPreferredName
45 | StringLocalSetting providesUserPreferredName(SharedPreferences preferences) {
46 | return new StringLocalSetting(preferences, "userPreferredName");
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/screen/SettingScreen.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.screen;
2 |
3 | import android.os.Bundle;
4 |
5 | import javax.inject.Inject;
6 | import javax.inject.Singleton;
7 |
8 | import co.moonmonkeylabs.flowmortarexampleapp.ActivityModule;
9 | import co.moonmonkeylabs.flowmortarexampleapp.R;
10 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.Layout;
11 | import co.moonmonkeylabs.flowmortarexampleapp.common.mortarscreen.WithModule;
12 | import co.moonmonkeylabs.flowmortarexampleapp.common.setting.StringLocalSetting;
13 | import co.moonmonkeylabs.flowmortarexampleapp.setting.UserPreferredName;
14 | import co.moonmonkeylabs.flowmortarexampleapp.view.SettingView;
15 | import flow.path.Path;
16 | import mortar.ViewPresenter;
17 |
18 | @Layout(R.layout.settings_layout)
19 | @WithModule(SettingScreen.Module.class)
20 | public class SettingScreen extends Path {
21 |
22 | @dagger.Module(injects = SettingView.class, addsTo = ActivityModule.class)
23 | public class Module {
24 | }
25 |
26 | @Singleton
27 | public static class Presenter extends ViewPresenter {
28 |
29 | private final StringLocalSetting userPreferredName;
30 |
31 | @Inject
32 | public Presenter(@UserPreferredName StringLocalSetting userPreferredName) {
33 | this.userPreferredName = userPreferredName;
34 | }
35 |
36 | @Override
37 | protected void onLoad(Bundle savedInstanceState) {
38 | super.onLoad(savedInstanceState);
39 |
40 | getView().updatePreferredName(userPreferredName.get());
41 | }
42 |
43 | public void handleSaveUserPreferredName(String newUserPreferredNameValue) {
44 | userPreferredName.set(newUserPreferredNameValue);
45 | }
46 | }
47 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/flow/Utils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package co.moonmonkeylabs.flowmortarexampleapp.common.flow;
18 |
19 | import android.view.View;
20 | import android.view.ViewTreeObserver;
21 |
22 | public final class Utils {
23 | public interface OnMeasuredCallback {
24 | void onMeasured(View view, int width, int height);
25 | }
26 |
27 | public static void waitForMeasure(final View view, final OnMeasuredCallback callback) {
28 | int width = view.getWidth();
29 | int height = view.getHeight();
30 |
31 | if (width > 0 && height > 0) {
32 | callback.onMeasured(view, width, height);
33 | return;
34 | }
35 |
36 | view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
37 | @Override public boolean onPreDraw() {
38 | final ViewTreeObserver observer = view.getViewTreeObserver();
39 | if (observer.isAlive()) {
40 | observer.removeOnPreDrawListener(this);
41 | }
42 |
43 | callback.onMeasured(view, view.getWidth(), view.getHeight());
44 |
45 | return true;
46 | }
47 | });
48 | }
49 |
50 | private Utils() {
51 | }
52 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/ApplicationModule.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package co.moonmonkeylabs.flowmortarexampleapp;
17 |
18 | import android.app.Application;
19 |
20 | import com.google.gson.Gson;
21 | import com.google.gson.GsonBuilder;
22 |
23 | import javax.inject.Singleton;
24 |
25 | import co.moonmonkeylabs.flowmortarexampleapp.common.actionbar.ActionBarOwner;
26 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.GsonParceler;
27 | import co.moonmonkeylabs.flowmortarexampleapp.setting.SettingsModule;
28 | import dagger.Module;
29 | import dagger.Provides;
30 | import flow.StateParceler;
31 |
32 | /**
33 | * Defines app-wide singletons
34 | */
35 | @Module(
36 | includes = {
37 | ActionBarOwner.ActionBarModule.class,
38 | SettingsModule.class
39 | },
40 | injects = FlowMortarExampleActivity.class,
41 | library = true)
42 | public class ApplicationModule {
43 |
44 | private final Application application;
45 |
46 | public ApplicationModule(Application application) {
47 | this.application = application;
48 | }
49 |
50 | @Provides
51 | public Application providesApplication() {
52 | return application;
53 | }
54 |
55 | @Provides
56 | @Singleton
57 | Gson provideGson() {
58 | return new GsonBuilder().create();
59 | }
60 |
61 | @Provides
62 | @Singleton
63 | StateParceler provideParcer(Gson gson) {
64 | return new GsonParceler(gson);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/screen/Wizard2Screen.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.screen;
2 |
3 | import android.app.Activity;
4 | import android.content.ContextWrapper;
5 | import android.os.Bundle;
6 |
7 | import javax.inject.Inject;
8 | import javax.inject.Singleton;
9 |
10 | import co.moonmonkeylabs.flowmortarexampleapp.FlowMortarExampleActivity;
11 | import co.moonmonkeylabs.flowmortarexampleapp.R;
12 | import co.moonmonkeylabs.flowmortarexampleapp.WizardModule;
13 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.ActivityHelper;
14 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.Layout;
15 | import co.moonmonkeylabs.flowmortarexampleapp.common.mortarscreen.WithModule;
16 | import co.moonmonkeylabs.flowmortarexampleapp.model.WizardState;
17 | import co.moonmonkeylabs.flowmortarexampleapp.view.Wizard2View;
18 | import flow.Flow;
19 | import flow.path.Path;
20 | import mortar.ViewPresenter;
21 |
22 | @Layout(R.layout.wizard_2_layout)
23 | @WithModule(Wizard2Screen.Module.class)
24 | public class Wizard2Screen extends Path {
25 |
26 | public Wizard2Screen() {
27 | }
28 |
29 | @dagger.Module(injects = Wizard2View.class, addsTo = WizardModule.class)
30 | public class Module {
31 | }
32 |
33 | @Singleton
34 | public static class Presenter extends ViewPresenter {
35 |
36 | private final WizardState wizardState;
37 | private final ActivityHelper activityHelper;
38 |
39 | @Inject
40 | public Presenter(WizardState wizardState, ActivityHelper activityHelper) {
41 | this.wizardState = wizardState;
42 | this.activityHelper = activityHelper;
43 | }
44 |
45 | @Override
46 | protected void onLoad(Bundle savedInstanceState) {
47 | super.onLoad(savedInstanceState);
48 |
49 | getView().updateWizardCount(++wizardState.count);
50 | }
51 |
52 | public void handleNextButtonClicked() {
53 | Activity activity = activityHelper.findActivity((ContextWrapper) getView().getContext());
54 | ((FlowMortarExampleActivity) activity).removeWizardScope();
55 | Flow.get(getView()).set(new MainScreen());
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/screen/Wizard1Screen.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.screen;
2 |
3 | import android.app.Activity;
4 | import android.content.ContextWrapper;
5 | import android.os.Bundle;
6 |
7 | import javax.inject.Inject;
8 | import javax.inject.Singleton;
9 |
10 | import co.moonmonkeylabs.flowmortarexampleapp.FlowMortarExampleActivity;
11 | import co.moonmonkeylabs.flowmortarexampleapp.R;
12 | import co.moonmonkeylabs.flowmortarexampleapp.WizardModule;
13 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.ActivityHelper;
14 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.Layout;
15 | import co.moonmonkeylabs.flowmortarexampleapp.common.mortarscreen.WithModule;
16 | import co.moonmonkeylabs.flowmortarexampleapp.model.WizardState;
17 | import co.moonmonkeylabs.flowmortarexampleapp.view.Wizard1View;
18 | import flow.Flow;
19 | import flow.path.Path;
20 | import mortar.ViewPresenter;
21 |
22 | @Layout(R.layout.wizard_1_layout)
23 | @WithModule(Wizard1Screen.Module.class)
24 | public class Wizard1Screen extends Path {
25 |
26 | public Wizard1Screen() {
27 | }
28 |
29 | @dagger.Module(injects = Wizard1View.class, addsTo = WizardModule.class)
30 | public class Module {
31 | }
32 |
33 | @Singleton
34 | public static class Presenter extends ViewPresenter {
35 |
36 | private final WizardState wizardState;
37 | private final ActivityHelper activityHelper;
38 |
39 | @Inject
40 | public Presenter(WizardState wizardState, ActivityHelper activityHelper) {
41 | this.wizardState = wizardState;
42 | this.activityHelper = activityHelper;
43 | }
44 |
45 | @Override
46 | protected void onLoad(Bundle savedInstanceState) {
47 | super.onLoad(savedInstanceState);
48 | getView().updateWizardCount(++wizardState.count);
49 | }
50 |
51 | public void handleNextButtonClicked() {
52 | Flow.get(getView()).set(new Wizard2Screen());
53 | }
54 |
55 | public void handleBackPressed() {
56 | Activity activity = activityHelper.findActivity((ContextWrapper) getView().getContext());
57 | ((FlowMortarExampleActivity) activity).removeWizardScope();
58 | }
59 | }
60 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/flowmortar/MortarContextFactory.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.common.flowmortar;
2 |
3 | import android.content.Context;
4 | import android.content.ContextWrapper;
5 | import android.view.LayoutInflater;
6 |
7 |
8 | import co.moonmonkeylabs.flowmortarexampleapp.FlowMortarExampleActivity;
9 | import co.moonmonkeylabs.flowmortarexampleapp.common.mortarscreen.ScreenScoper;
10 | import flow.path.Path;
11 | import flow.path.PathContextFactory;
12 | import mortar.MortarScope;
13 |
14 | public final class MortarContextFactory implements PathContextFactory {
15 | private final ScreenScoper screenScoper = new ScreenScoper();
16 |
17 | public MortarContextFactory() {
18 | }
19 |
20 | @Override public Context setUpContext(Path path, Context parentContext) {
21 | // TODO - Figure out if hook for additional scope tear down should go here
22 |
23 | MortarScope screenScope =
24 | screenScoper.getScreenScope(parentContext, path.getClass().getName(), path);
25 | return new TearDownContext(parentContext, screenScope);
26 | }
27 |
28 | @Override public void tearDownContext(Context context) {
29 | TearDownContext.destroyScope(context);
30 | }
31 |
32 | static class TearDownContext extends ContextWrapper {
33 | private static final String SERVICE = "SNEAKY_MORTAR_PARENT_HOOK";
34 | private final MortarScope parentScope;
35 | private LayoutInflater inflater;
36 |
37 | static void destroyScope(Context context) {
38 | MortarScope scope = MortarScope.getScope(context);
39 | if (scope.getName().startsWith(FlowMortarExampleActivity.class.getSimpleName())) {
40 | return;
41 | }
42 | scope.destroy();
43 | }
44 |
45 | public TearDownContext(Context context, MortarScope scope) {
46 | super(scope.createContext(context));
47 | this.parentScope = MortarScope.getScope(context);
48 | }
49 |
50 | @Override public Object getSystemService(String name) {
51 | if (LAYOUT_INFLATER_SERVICE.equals(name)) {
52 | if (inflater == null) {
53 | inflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
54 | }
55 | return inflater;
56 | }
57 |
58 | if (SERVICE.equals(name)) {
59 | return parentScope;
60 | }
61 |
62 | return super.getSystemService(name);
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/screen/MainScreen.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.screen;
2 |
3 | import android.app.Activity;
4 | import android.content.ContextWrapper;
5 | import android.os.Bundle;
6 |
7 | import javax.inject.Inject;
8 | import javax.inject.Singleton;
9 |
10 | import co.moonmonkeylabs.flowmortarexampleapp.ActivityModule;
11 | import co.moonmonkeylabs.flowmortarexampleapp.FlowMortarExampleActivity;
12 | import co.moonmonkeylabs.flowmortarexampleapp.R;
13 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.ActivityHelper;
14 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.Layout;
15 | import co.moonmonkeylabs.flowmortarexampleapp.common.mortarscreen.WithModule;
16 | import co.moonmonkeylabs.flowmortarexampleapp.view.MainView;
17 | import flow.Flow;
18 | import flow.path.Path;
19 | import mortar.ViewPresenter;
20 |
21 | @Layout(R.layout.main_layout)
22 | @WithModule(MainScreen.Module.class)
23 | public class MainScreen extends Path {
24 |
25 | @Override
26 | public boolean equals(Object o) {
27 | if (o == null) {
28 | return false;
29 | }
30 | return this.getClass().getSimpleName().equals(o.getClass().getSimpleName());
31 | }
32 |
33 | @dagger.Module(injects = MainView.class, addsTo = ActivityModule.class)
34 | public class Module {
35 | }
36 |
37 | @Singleton
38 | public static class Presenter extends ViewPresenter {
39 |
40 | private final ActivityHelper activityHelper;
41 |
42 | @Inject
43 | public Presenter(ActivityHelper activityHelper) {
44 | this.activityHelper = activityHelper;
45 | }
46 |
47 | @Override
48 | protected void onLoad(Bundle savedInstanceState) {
49 | super.onLoad(savedInstanceState);
50 | }
51 |
52 | @Override
53 | protected void onSave(Bundle outState) {
54 | super.onSave(outState);
55 | }
56 |
57 | public void handleRotationScreenButtonClicked() {
58 | Flow.get(getView()).set(new RotationScreen());
59 | }
60 |
61 | public void handlePhotoDisplayScreenButtonClicked() {
62 | Flow.get(getView()).set(new PhotoDisplayScreen());
63 | }
64 |
65 | public void handleSettingsScreenButtonClicked() {
66 | Flow.get(getView()).set(new SettingScreen());
67 | }
68 |
69 | public void handleWizardScreenButtonClicked() {
70 | Activity activity = activityHelper.findActivity((ContextWrapper) getView().getContext());
71 | ((FlowMortarExampleActivity) activity).addWizardScope();
72 |
73 | Flow.get(getView()).set(new Wizard1Screen());
74 | }
75 | }
76 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/flow/FramePathContainerView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package co.moonmonkeylabs.flowmortarexampleapp.common.flow;
18 |
19 | import android.content.Context;
20 | import android.util.AttributeSet;
21 | import android.view.MotionEvent;
22 | import android.view.ViewGroup;
23 | import android.widget.FrameLayout;
24 |
25 | import co.moonmonkeylabs.flowmortarexampleapp.R;
26 | import flow.Flow;
27 | import flow.path.Path;
28 | import flow.path.PathContainer;
29 | import flow.path.PathContainerView;
30 |
31 |
32 | /** A FrameLayout that can show screens for a {@link flow.Flow}. */
33 | public class FramePathContainerView extends FrameLayout
34 | implements HandlesBack, PathContainerView {
35 | private final PathContainer container;
36 | private boolean disabled;
37 |
38 | @SuppressWarnings("UnusedDeclaration") // Used by layout inflation, of course!
39 | public FramePathContainerView(Context context, AttributeSet attrs) {
40 | this(context, attrs, new SimplePathContainer(R.id.screen_switcher_tag, Path.contextFactory()));
41 | }
42 |
43 | /**
44 | * Allows subclasses to use custom {@link flow.path.PathContainer} implementations. Allows the use
45 | * of more sophisticated transition schemes, and customized context wrappers.
46 | */
47 | protected FramePathContainerView(Context context, AttributeSet attrs, PathContainer container) {
48 | super(context, attrs);
49 | this.container = container;
50 | }
51 |
52 | @Override public boolean dispatchTouchEvent(MotionEvent ev) {
53 | return !disabled && super.dispatchTouchEvent(ev);
54 | }
55 |
56 | @Override public ViewGroup getContainerView() {
57 | return this;
58 | }
59 |
60 | @Override protected void onFinishInflate() {
61 | super.onFinishInflate();
62 | }
63 |
64 | @Override public void dispatch(Flow.Traversal traversal, final Flow.TraversalCallback callback) {
65 | disabled = true;
66 | container.executeTraversal(this, traversal, new Flow.TraversalCallback() {
67 | @Override public void onTraversalCompleted() {
68 | callback.onTraversalCompleted();
69 | disabled = false;
70 | }
71 | });
72 | }
73 |
74 | @Override public boolean onBackPressed() {
75 | return BackSupport.onBackPressed(getCurrentChild());
76 | }
77 |
78 | @Override public ViewGroup getCurrentChild() {
79 | return (ViewGroup) getContainerView().getChildAt(0);
80 | }
81 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/screen/PhotoDisplayScreen.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.screen;
2 |
3 | import android.app.Activity;
4 | import android.content.ContextWrapper;
5 | import android.content.Intent;
6 | import android.graphics.Bitmap;
7 | import android.graphics.BitmapFactory;
8 | import android.net.Uri;
9 | import android.os.Bundle;
10 | import android.widget.Toast;
11 |
12 | import java.io.FileNotFoundException;
13 | import java.io.InputStream;
14 |
15 | import javax.inject.Inject;
16 | import javax.inject.Singleton;
17 |
18 | import co.moonmonkeylabs.flowmortarexampleapp.ActivityModule;
19 | import co.moonmonkeylabs.flowmortarexampleapp.R;
20 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.ActivityHelper;
21 | import co.moonmonkeylabs.flowmortarexampleapp.common.flow.Layout;
22 | import co.moonmonkeylabs.flowmortarexampleapp.common.lifecycle.LifecycleOwner;
23 | import co.moonmonkeylabs.flowmortarexampleapp.common.lifecycle.LifecycleViewPresenter;
24 | import co.moonmonkeylabs.flowmortarexampleapp.common.mortarscreen.WithModule;
25 | import co.moonmonkeylabs.flowmortarexampleapp.view.PhotoDisplayView;
26 | import flow.path.Path;
27 | import flow.path.PathContext;
28 |
29 | @Layout(R.layout.photo_display_layout)
30 | @WithModule(PhotoDisplayScreen.Module.class)
31 | public class PhotoDisplayScreen extends Path {
32 |
33 | @dagger.Module(injects = PhotoDisplayView.class, addsTo = ActivityModule.class)
34 | public class Module {
35 | }
36 |
37 | @Singleton
38 | public static class Presenter extends LifecycleViewPresenter {
39 |
40 | private static final int SELECT_PICTURE = 1;
41 |
42 | private final ActivityHelper activityHelper;
43 |
44 | @Inject
45 | public Presenter(LifecycleOwner lifecycleOwner, ActivityHelper activityHelper) {
46 | super(lifecycleOwner);
47 | this.activityHelper = activityHelper;
48 | }
49 |
50 | public void handlePhotoDisplayPickButtonClicked() {
51 | Intent intent = new Intent();
52 | intent.setType("image/*");
53 | intent.setAction(Intent.ACTION_GET_CONTENT);
54 | Activity activity = activityHelper.findActivity((ContextWrapper) getView().getContext());
55 | activity.startActivityForResult(
56 | Intent.createChooser(intent, "Select Picture"),
57 | SELECT_PICTURE);
58 | }
59 |
60 | @Override
61 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
62 | if (requestCode == SELECT_PICTURE) {
63 | try {
64 | final Uri imageUri = data.getData();
65 | Activity activity = activityHelper.findActivity((ContextWrapper) getView().getContext());
66 | final InputStream imageStream =
67 | activity.getContentResolver().openInputStream(imageUri);
68 | final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
69 | getView().setImage(selectedImage);
70 | } catch (FileNotFoundException e) {
71 | Toast.makeText(getView().getContext(), "Failed to load image", Toast.LENGTH_SHORT).show();
72 | }
73 | }
74 | }
75 | }
76 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/lifecycle/LifecycleOwner.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.common.lifecycle;
2 |
3 | import android.content.Intent;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | import javax.annotation.Nonnull;
9 | import javax.inject.Inject;
10 | import javax.inject.Singleton;
11 |
12 | /**
13 | * Pass along the Android lifecycle events.
14 | * Tip to http://stackoverflow.com/questions/21927990/mortar-flow-with-third-party-libraries-hooked-to-activity-lifecycle/21959529?noredirect=1#21959529
15 | * on this one, mostly.
16 | */
17 | @Singleton
18 | public class LifecycleOwner implements ActivityLifecycleListener {
19 |
20 | private List registeredListeners
21 | = new ArrayList<>();
22 |
23 | @Inject
24 | public LifecycleOwner() {
25 | }
26 |
27 | public void register(@Nonnull ActivityLifecycleListener listener) {
28 | registeredListeners.add(listener);
29 | }
30 |
31 | public void unregister(@Nonnull ActivityLifecycleListener listener) {
32 | registeredListeners.remove(listener);
33 | }
34 |
35 | @Override public void onActivityResume() {
36 | ActivityLifecycleListener[] lifecycleListeners = getArrayCopyOfRegisteredListeners();
37 | for (ActivityLifecycleListener c : lifecycleListeners) {
38 | c.onActivityResume();
39 | }
40 | }
41 |
42 | @Override public void onActivityPause() {
43 | ActivityLifecycleListener[] lifecycleListeners = getArrayCopyOfRegisteredListeners();
44 | for (ActivityLifecycleListener c : lifecycleListeners) {
45 | c.onActivityPause();
46 | }
47 | }
48 |
49 | @Override public void onActivityStart() {
50 | ActivityLifecycleListener[] lifecycleListeners = getArrayCopyOfRegisteredListeners();
51 | for (ActivityLifecycleListener c : lifecycleListeners) {
52 | c.onActivityStart();
53 | }
54 | }
55 |
56 | @Override public void onActivityStop() {
57 | ActivityLifecycleListener[] lifecycleListeners = getArrayCopyOfRegisteredListeners();
58 | for (ActivityLifecycleListener c : lifecycleListeners) {
59 | c.onActivityStop();
60 | }
61 | }
62 |
63 | @Override
64 | public void onLowMemory() {
65 | ActivityLifecycleListener[] lifecycleListeners = getArrayCopyOfRegisteredListeners();
66 | for (ActivityLifecycleListener c : lifecycleListeners) {
67 | c.onLowMemory();
68 | }
69 | }
70 |
71 | @Override
72 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
73 | ActivityLifecycleListener[] lifecycleListeners = getArrayCopyOfRegisteredListeners();
74 | for (ActivityLifecycleListener c : lifecycleListeners) {
75 | c.onActivityResult(requestCode, resultCode, data);
76 | }
77 | }
78 |
79 | /**
80 | * Creates a copy of the {@link #registeredListeners} list in order to safely iterate the
81 | * listeners. This was added to avoid {@link java.util.ConcurrentModificationException} that may
82 | * be triggered when listeners are added / removed during one of the lifecycle events.
83 | */
84 | private ActivityLifecycleListener[] getArrayCopyOfRegisteredListeners() {
85 | ActivityLifecycleListener[] registeredListenersArray =
86 | new ActivityLifecycleListener[registeredListeners.size()];
87 | registeredListeners.toArray(registeredListenersArray);
88 | return registeredListenersArray;
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/flow/GsonParceler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package co.moonmonkeylabs.flowmortarexampleapp.common.flow;
17 |
18 | import android.os.Parcel;
19 | import android.os.Parcelable;
20 |
21 | import com.google.gson.Gson;
22 | import com.google.gson.stream.JsonReader;
23 | import com.google.gson.stream.JsonWriter;
24 |
25 | import java.io.IOException;
26 | import java.io.StringReader;
27 | import java.io.StringWriter;
28 |
29 | import flow.StateParceler;
30 |
31 | public class GsonParceler implements StateParceler {
32 | private final Gson gson;
33 |
34 | public GsonParceler(Gson gson) {
35 | this.gson = gson;
36 | }
37 |
38 | @Override public Parcelable wrap(Object instance) {
39 | try {
40 | String json = encode(instance);
41 | return new Wrapper(json);
42 | } catch (IOException e) {
43 | throw new RuntimeException(e);
44 | }
45 | }
46 |
47 | @Override public Object unwrap(Parcelable parcelable) {
48 | Wrapper wrapper = (Wrapper) parcelable;
49 | try {
50 | return decode(wrapper.json);
51 | } catch (IOException e) {
52 | throw new RuntimeException(e);
53 | }
54 | }
55 |
56 | private String encode(Object instance) throws IOException {
57 | StringWriter stringWriter = new StringWriter();
58 | JsonWriter writer = new JsonWriter(stringWriter);
59 |
60 | try {
61 | Class> type = instance.getClass();
62 |
63 | writer.beginObject();
64 | writer.name(type.getName());
65 | gson.toJson(instance, type, writer);
66 | writer.endObject();
67 |
68 | return stringWriter.toString();
69 | } finally {
70 | writer.close();
71 | }
72 | }
73 |
74 | private Object decode(String json) throws IOException {
75 | JsonReader reader = new JsonReader(new StringReader(json));
76 |
77 | try {
78 | reader.beginObject();
79 |
80 | Class> type = Class.forName(reader.nextName());
81 | return gson.fromJson(reader, type);
82 | } catch (ClassNotFoundException e) {
83 | throw new RuntimeException(e);
84 | } finally {
85 | reader.close();
86 | }
87 | }
88 |
89 | private static class Wrapper implements Parcelable {
90 | final String json;
91 |
92 | Wrapper(String json) {
93 | this.json = json;
94 | }
95 |
96 | @Override public int describeContents() {
97 | return 0;
98 | }
99 |
100 | @Override public void writeToParcel(Parcel out, int flags) {
101 | out.writeString(json);
102 | }
103 |
104 | public static final Creator CREATOR = new Creator() {
105 | @Override public Wrapper createFromParcel(Parcel in) {
106 | String json = in.readString();
107 | return new Wrapper(json);
108 | }
109 |
110 | @Override public Wrapper[] newArray(int size) {
111 | return new Wrapper[size];
112 | }
113 | };
114 | }
115 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/actionbar/ActionBarOwner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package co.moonmonkeylabs.flowmortarexampleapp.common.actionbar;
17 |
18 | import android.content.Context;
19 | import android.os.Bundle;
20 |
21 | import javax.inject.Singleton;
22 |
23 | import dagger.Module;
24 | import dagger.Provides;
25 | import mortar.Presenter;
26 | import mortar.bundler.BundleService;
27 | import rx.functions.Action0;
28 |
29 | import static mortar.bundler.BundleService.getBundleService;
30 |
31 | /** Allows shared configuration of the Android ActionBar. */
32 | public class ActionBarOwner extends Presenter {
33 | public interface Activity {
34 | void setShowHomeEnabled(boolean enabled);
35 |
36 | void setUpButtonEnabled(boolean enabled);
37 |
38 | void setTitle(CharSequence title);
39 |
40 | void setMenu(MenuAction action);
41 |
42 | Context getContext();
43 | }
44 |
45 | public static class Config {
46 | public final boolean showHomeEnabled;
47 | public final boolean upButtonEnabled;
48 | public final CharSequence title;
49 | public final MenuAction action;
50 |
51 | public Config(boolean showHomeEnabled, boolean upButtonEnabled, CharSequence title,
52 | MenuAction action) {
53 | this.showHomeEnabled = showHomeEnabled;
54 | this.upButtonEnabled = upButtonEnabled;
55 | this.title = title;
56 | this.action = action;
57 | }
58 |
59 | public Config withAction(MenuAction action) {
60 | return new Config(showHomeEnabled, upButtonEnabled, title, action);
61 | }
62 | }
63 |
64 | public static class MenuAction {
65 | public final CharSequence title;
66 | public final Action0 action;
67 |
68 | public MenuAction(CharSequence title, Action0 action) {
69 | this.title = title;
70 | this.action = action;
71 | }
72 | }
73 |
74 | private Config config;
75 |
76 | ActionBarOwner() {
77 | }
78 |
79 | @Override public void onLoad(Bundle savedInstanceState) {
80 | if (config != null) update();
81 | }
82 |
83 | public void setConfig(Config config) {
84 | this.config = config;
85 | update();
86 | }
87 |
88 | public Config getConfig() {
89 | return config;
90 | }
91 |
92 | @Override protected BundleService extractBundleService(Activity activity) {
93 | return getBundleService(activity.getContext());
94 | }
95 |
96 | private void update() {
97 | if (!hasView()) return;
98 | Activity activity = getView();
99 |
100 | activity.setShowHomeEnabled(config.showHomeEnabled);
101 | activity.setUpButtonEnabled(config.upButtonEnabled);
102 | activity.setTitle(config.title);
103 | activity.setMenu(config.action);
104 | }
105 |
106 | @Module(library = true)
107 | public static class ActionBarModule {
108 | @Provides @Singleton ActionBarOwner provideActionBarOwner() {
109 | return new ActionBarOwner();
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/dagger/ObjectGraphService.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.common.dagger;
2 |
3 | import android.content.Context;
4 |
5 | import java.util.Collection;
6 |
7 | import dagger.ObjectGraph;
8 | import mortar.MortarScope;
9 | import mortar.bundler.BundleServiceRunner;
10 |
11 | /**
12 | * Provides utility methods for using Mortar with Dagger 1.
13 | */
14 | public class ObjectGraphService {
15 | public static final String SERVICE_NAME = ObjectGraphService.class.getName();
16 |
17 | /**
18 | * Create a new {@link ObjectGraph} based on the given module. The new graph will extend
19 | * the graph found in the parent scope (via {@link ObjectGraph#plus}), if there is one.
20 | */
21 | public static ObjectGraph create(MortarScope parent, Object... daggerModules) {
22 | ObjectGraph parentGraph = getObjectGraph(parent);
23 |
24 | return parentGraph == null ? ObjectGraph.create(daggerModules)
25 | : parentGraph.plus(daggerModules);
26 | }
27 |
28 | public static ObjectGraph getObjectGraph(Context context) {
29 | return (ObjectGraph) context.getSystemService(ObjectGraphService.SERVICE_NAME);
30 | }
31 |
32 | public static ObjectGraph getObjectGraph(MortarScope scope) {
33 | return scope.getService(ObjectGraphService.SERVICE_NAME);
34 | }
35 |
36 | /**
37 | * A convenience wrapper for {@link ObjectGraphService#getObjectGraph} to simplify dynamic
38 | * injection, typically for {@link android.app.Activity} and {@link android.view.View} instances that must be
39 | * instantiated by Android.
40 | */
41 | public static void inject(Context context, Object object) {
42 | getObjectGraph(context).inject(object);
43 | }
44 |
45 | /**
46 | * A convenience wrapper for {@link ObjectGraphService#getObjectGraph} to simplify dynamic
47 | * injection, typically for {@link android.app.Activity} and {@link android.view.View} instances that must be
48 | * instantiated by Android.
49 | */
50 | public static void inject(MortarScope scope, Object object) {
51 | getObjectGraph(scope).inject(object);
52 | }
53 |
54 | private static ObjectGraph createSubgraphBlueprintStyle(ObjectGraph parentGraph,
55 | Object daggerModule) {
56 | ObjectGraph newGraph;
57 | if (daggerModule == null) {
58 | newGraph = parentGraph.plus();
59 | } else if (daggerModule instanceof Collection) {
60 | Collection c = (Collection) daggerModule;
61 | newGraph = parentGraph.plus(c.toArray(new Object[c.size()]));
62 | } else {
63 | newGraph = parentGraph.plus(daggerModule);
64 | }
65 | return newGraph;
66 | }
67 |
68 | /**
69 | * Returns the existing {@link MortarScope} scope for the given {@link android.app.Activity}, or
70 | * uses the {@link Blueprint} to create one if none is found. The scope will provide
71 | * {@link mortar.bundler.BundleService} and {@link BundleServiceRunner}.
72 | *
73 | * It is expected that this method will be called from {@link android.app.Activity#onCreate}. Calling
74 | * it at other times may lead to surprises.
75 | *
76 | * @see MortarScope.Builder#withService(String, Object)
77 | * @deprecated This method is provided to ease migration from earlier releases, which
78 | * coupled Dagger and Activity integration. Instead build new scopes with {@link
79 | * MortarScope#buildChild()}, and bind {@link ObjectGraphService} and
80 | * {@link BundleServiceRunner} instances to them.
81 | */
82 | @Deprecated public static MortarScope requireActivityScope(MortarScope parentScope,
83 | Blueprint blueprint) {
84 | String childName = blueprint.getMortarScopeName();
85 | MortarScope child = parentScope.findChild(childName);
86 | if (child == null) {
87 | ObjectGraph parentGraph = parentScope.getService(ObjectGraphService.SERVICE_NAME);
88 | Object daggerModule = blueprint.getDaggerModule();
89 | Object childGraph = createSubgraphBlueprintStyle(parentGraph, daggerModule);
90 | child = parentScope.buildChild()
91 | .withService(ObjectGraphService.SERVICE_NAME, childGraph)
92 | .withService(BundleServiceRunner.SERVICE_NAME, new BundleServiceRunner())
93 | .build(childName);
94 | }
95 | return child;
96 | }
97 |
98 | /**
99 | * Returns the existing child whose name matches the given {@link Blueprint}'s
100 | * {@link Blueprint#getMortarScopeName()} value. If there is none, a new child is created
101 | * based on {@link Blueprint#getDaggerModule()}. Note that
102 | * {@link Blueprint#getDaggerModule()} is not called otherwise.
103 | *
104 | * @throws IllegalStateException if this scope has been destroyed
105 | * @see MortarScope.Builder#withService(String, Object)
106 | * @deprecated This method is provided to ease migration from earlier releases, which
107 | * required Dagger integration. Instead build new scopes with {@link
108 | * MortarScope#buildChild()}, and bind {@link ObjectGraphService} instances to them.
109 | */
110 | @Deprecated public static MortarScope requireChild(MortarScope parentScope, Blueprint blueprint) {
111 | String childName = blueprint.getMortarScopeName();
112 | MortarScope child = parentScope.findChild(childName);
113 | if (child == null) {
114 | ObjectGraph parentGraph = parentScope.getService(ObjectGraphService.SERVICE_NAME);
115 | Object daggerModule = blueprint.getDaggerModule();
116 | Object childGraph = createSubgraphBlueprintStyle(parentGraph, daggerModule);
117 | child = parentScope.buildChild()
118 | .withService(ObjectGraphService.SERVICE_NAME, childGraph)
119 | .build(childName);
120 | }
121 | return child;
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/flow/SimplePathContainer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package co.moonmonkeylabs.flowmortarexampleapp.common.flow;
18 |
19 | import android.animation.Animator;
20 | import android.animation.AnimatorListenerAdapter;
21 | import android.animation.AnimatorSet;
22 | import android.animation.ObjectAnimator;
23 | import android.view.LayoutInflater;
24 | import android.view.View;
25 | import android.view.ViewGroup;
26 |
27 | import java.util.LinkedHashMap;
28 | import java.util.Map;
29 |
30 | import flow.Flow;
31 | import flow.path.Path;
32 | import flow.path.PathContainer;
33 | import flow.path.PathContext;
34 | import flow.path.PathContextFactory;
35 |
36 | import static flow.Flow.Direction.REPLACE;
37 |
38 | /**
39 | * Provides basic right-to-left transitions. Saves and restores view state.
40 | * Uses {@link flow.path.PathContext} to allow customized sub-containers.
41 | */
42 | public class SimplePathContainer extends PathContainer {
43 | private static final Map PATH_LAYOUT_CACHE = new LinkedHashMap<>();
44 | private final PathContextFactory contextFactory;
45 |
46 | public SimplePathContainer(int tagKey, PathContextFactory contextFactory) {
47 | super(tagKey);
48 | this.contextFactory = contextFactory;
49 | }
50 |
51 | @Override protected void performTraversal(final ViewGroup containerView,
52 | final TraversalState traversalState, final Flow.Direction direction,
53 | final Flow.TraversalCallback callback) {
54 |
55 | final PathContext context;
56 | final PathContext oldPath;
57 | if (containerView.getChildCount() > 0) {
58 | oldPath = PathContext.get(containerView.getChildAt(0).getContext());
59 | } else {
60 | oldPath = PathContext.root(containerView.getContext());
61 | }
62 |
63 | Path to = traversalState.toPath();
64 |
65 | View newView;
66 | context = PathContext.create(oldPath, to, contextFactory);
67 | int layout = getLayout(to);
68 | newView = LayoutInflater.from(context)
69 | .cloneInContext(context)
70 | .inflate(layout, containerView, false);
71 |
72 | View fromView = null;
73 | if (traversalState.fromPath() != null) {
74 | fromView = containerView.getChildAt(0);
75 | traversalState.saveViewState(fromView);
76 | }
77 | traversalState.restoreViewState(newView);
78 |
79 | if (fromView == null || direction == REPLACE) {
80 | containerView.removeAllViews();
81 | containerView.addView(newView);
82 | oldPath.destroyNotIn(context, contextFactory);
83 | callback.onTraversalCompleted();
84 | } else {
85 | containerView.addView(newView);
86 | final View finalFromView = fromView;
87 | Utils.waitForMeasure(newView, new Utils.OnMeasuredCallback() {
88 | @Override public void onMeasured(View view, int width, int height) {
89 | runAnimation(containerView, finalFromView, view, direction, new Flow.TraversalCallback() {
90 | @Override public void onTraversalCompleted() {
91 | containerView.removeView(finalFromView);
92 | oldPath.destroyNotIn(context, contextFactory);
93 | callback.onTraversalCompleted();
94 | }
95 | });
96 | }
97 | });
98 | }
99 | }
100 |
101 | protected int getLayout(Path path) {
102 | Class pathType = path.getClass();
103 | Integer layoutResId = PATH_LAYOUT_CACHE.get(pathType);
104 | if (layoutResId == null) {
105 | Layout layout = (Layout) pathType.getAnnotation(Layout.class);
106 | if (layout == null) {
107 | throw new IllegalArgumentException(
108 | String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
109 | pathType.getName()));
110 | }
111 | layoutResId = layout.value();
112 | PATH_LAYOUT_CACHE.put(pathType, layoutResId);
113 | }
114 | return layoutResId;
115 | }
116 |
117 | private void runAnimation(final ViewGroup container, final View from, final View to,
118 | Flow.Direction direction, final Flow.TraversalCallback callback) {
119 | Animator animator = createAnimatorScale(from, to, direction);
120 | animator.addListener(new AnimatorListenerAdapter() {
121 | @Override public void onAnimationEnd(Animator animation) {
122 | container.removeView(from);
123 | callback.onTraversalCompleted();
124 | }
125 | });
126 | animator.start();
127 | }
128 |
129 | private Animator createAnimatorScale(View from, View to, Flow.Direction direction) {
130 | AnimatorSet set = new AnimatorSet();
131 |
132 | set.play(ObjectAnimator.ofFloat(from, View.SCALE_X, 1, 0))
133 | .with(ObjectAnimator.ofFloat(from, View.SCALE_Y, 1, 0));
134 | set.play(ObjectAnimator.ofFloat(to, View.SCALE_X, 0, 1))
135 | .with(ObjectAnimator.ofFloat(to, View.SCALE_Y, 0, 1));
136 |
137 | return set;
138 | }
139 |
140 | private Animator createAnimatorSliding(View from, View to, Flow.Direction direction) {
141 | boolean backward = direction == Flow.Direction.BACKWARD;
142 | int fromTranslation = backward ? from.getWidth() : -from.getWidth();
143 | int toTranslation = backward ? -to.getWidth() : to.getWidth();
144 |
145 | AnimatorSet set = new AnimatorSet();
146 |
147 | set.play(ObjectAnimator.ofFloat(from, View.TRANSLATION_X, fromTranslation));
148 | set.play(ObjectAnimator.ofFloat(to, View.TRANSLATION_X, toTranslation, 0));
149 |
150 | return set;
151 | }
152 | }
--------------------------------------------------------------------------------
/app/src/main/java/co/moonmonkeylabs/flowmortarexampleapp/common/mortarscreen/ScreenScoper.java:
--------------------------------------------------------------------------------
1 | package co.moonmonkeylabs.flowmortarexampleapp.common.mortarscreen;
2 |
3 | import android.content.Context;
4 | import android.content.res.Resources;
5 |
6 | import java.lang.reflect.Constructor;
7 | import java.lang.reflect.InvocationTargetException;
8 | import java.util.LinkedHashMap;
9 | import java.util.Map;
10 |
11 | import co.moonmonkeylabs.flowmortarexampleapp.common.dagger.ObjectGraphService;
12 | import mortar.MortarScope;
13 |
14 | import static java.lang.String.format;
15 |
16 | /**
17 | * Creates {@link mortar.MortarScope}s for screens that may be annotated with {@link WithModuleFactory},
18 | * {@link WithModule}.
19 | */
20 | public class ScreenScoper {
21 | private static final ModuleFactory NO_FACTORY = new ModuleFactory() {
22 | @Override protected Object createDaggerModule(Resources resources, Object screen) {
23 | throw new UnsupportedOperationException();
24 | }
25 | };
26 |
27 | private final Map moduleFactoryCache = new LinkedHashMap<>();
28 |
29 | public MortarScope getScreenScope(Context context, String name, Object screen) {
30 | MortarScope parentScope = MortarScope.getScope(context);
31 | return getScreenScope(context.getResources(), parentScope, name, screen);
32 | }
33 |
34 | /**
35 | * Finds or creates the scope for the given screen, honoring its optional {@link
36 | * WithModuleFactory} or {@link WithModule} annotation. Note that scopes are also created
37 | * for unannotated screens.
38 | */
39 | public MortarScope getScreenScope(Resources resources, MortarScope parentScope, final String name,
40 | final Object screen) {
41 | ModuleFactory moduleFactory = getModuleFactory(screen);
42 | Object[] childModule;
43 | if (moduleFactory != NO_FACTORY) {
44 | childModule = new Object[]{ moduleFactory.createDaggerModule(resources, screen) };
45 | } else {
46 | // We need every screen to have a scope, so that anything it injects is scoped. We need
47 | // this even if the screen doesn't declare a module, because Dagger allows injection of
48 | // objects that are annotated even if they don't appear in a module.
49 | childModule = new Object[0];
50 | }
51 |
52 | MortarScope childScope = parentScope.findChild(name);
53 | if (childScope == null) {
54 | childScope = parentScope.buildChild()
55 | .withService(ObjectGraphService.SERVICE_NAME,
56 | ObjectGraphService.create(parentScope, childModule))
57 | .build(name);
58 | }
59 |
60 | return childScope;
61 | }
62 |
63 | private ModuleFactory getModuleFactory(Object screen) {
64 | Class> screenType = screen.getClass();
65 | ModuleFactory moduleFactory = moduleFactoryCache.get(screenType);
66 |
67 | if (moduleFactory != null) return moduleFactory;
68 |
69 | WithModule withModule = screenType.getAnnotation(WithModule.class);
70 | if (withModule != null) {
71 | Class> moduleClass = withModule.value();
72 |
73 | Constructor>[] constructors = moduleClass.getDeclaredConstructors();
74 |
75 | if (constructors.length != 1) {
76 | throw new IllegalArgumentException(
77 | format("Module %s for screen %s should have exactly one public constructor",
78 | moduleClass.getName(), screen));
79 | }
80 |
81 | Constructor constructor = constructors[0];
82 |
83 | Class[] parameters = constructor.getParameterTypes();
84 |
85 | if (parameters.length > 1) {
86 | throw new IllegalArgumentException(
87 | format("Module %s for screen %s should have 0 or 1 parameter", moduleClass.getName(),
88 | screen));
89 | }
90 |
91 | Class screenParameter;
92 | if (parameters.length == 1) {
93 | screenParameter = parameters[0];
94 | if (!screenParameter.isInstance(screen)) {
95 | throw new IllegalArgumentException(format("Module %s for screen %s should have a "
96 | + "constructor parameter that is a super class of %s", moduleClass.getName(),
97 | screen, screen.getClass().getName()));
98 | }
99 | } else {
100 | screenParameter = null;
101 | }
102 |
103 | try {
104 | if (screenParameter == null) {
105 | moduleFactory = new NoArgsFactory(constructor);
106 | } else {
107 | moduleFactory = new SingleArgFactory(constructor);
108 | }
109 | } catch (Exception e) {
110 | throw new RuntimeException(
111 | format("Failed to instantiate module %s for screen %s", moduleClass.getName(), screen),
112 | e);
113 | }
114 | }
115 |
116 | if (moduleFactory == null) {
117 | WithModuleFactory withModuleFactory = screenType.getAnnotation(WithModuleFactory.class);
118 | if (withModuleFactory != null) {
119 | Class extends ModuleFactory> mfClass = withModuleFactory.value();
120 |
121 | try {
122 | moduleFactory = mfClass.newInstance();
123 | } catch (Exception e) {
124 | throw new RuntimeException(format("Failed to instantiate module factory %s for screen %s",
125 | withModuleFactory.value().getName(), screen), e);
126 | }
127 | }
128 | }
129 |
130 | if (moduleFactory == null) moduleFactory = NO_FACTORY;
131 |
132 | moduleFactoryCache.put(screenType, moduleFactory);
133 |
134 | return moduleFactory;
135 | }
136 |
137 | private static class NoArgsFactory extends ModuleFactory