summaryrefslogtreecommitdiff
path: root/app/src/main/java/se/leap/bitmaskclient/providersetup/activities/ConfigWizardBaseActivity.java
blob: a0c046dee1b9b721c10c51c4605e2343917f190f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
package se.leap.bitmaskclient.providersetup.activities;

import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.Guideline;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

import butterknife.BindView;
import se.leap.bitmaskclient.R;
import se.leap.bitmaskclient.base.models.Provider;
import se.leap.bitmaskclient.base.views.ProviderHeaderView;
import se.leap.bitmaskclient.tor.TorStatusObservable;

import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE;
import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_KEY;
import static se.leap.bitmaskclient.base.models.Constants.SHARED_PREFERENCES;
import static se.leap.bitmaskclient.tor.TorStatusObservable.getBootstrapProgress;
import static se.leap.bitmaskclient.tor.TorStatusObservable.getLastLogs;
import static se.leap.bitmaskclient.tor.TorStatusObservable.getLastSnowflakeLog;
import static se.leap.bitmaskclient.tor.TorStatusObservable.getLastTorLog;
import static se.leap.bitmaskclient.tor.TorStatusObservable.getStringForCurrentStatus;

/**
 * Base Activity for configuration wizard activities
 *
 * Created by fupduck on 09.01.18.
 */

public abstract class ConfigWizardBaseActivity extends ButterKnifeActivity implements Observer {

    private static final String TAG = ConfigWizardBaseActivity.class.getName();
    public static final float GUIDE_LINE_COMPACT_DELTA = 0.1f;
    protected SharedPreferences preferences;

    @BindView(R.id.header)
    ProviderHeaderView providerHeaderView;

    //Add provider screen has no loading screen
    @Nullable
    @BindView(R.id.loading_screen)
    protected LinearLayout loadingScreen;

    @Nullable
    @BindView(R.id.btn_connection_detail)
    protected Button connectionDetailBtn;

    @Nullable
    @BindView(R.id.connection_detail_container)
    protected RelativeLayout connectionDetailContainer;

    @Nullable
    @BindView(R.id.log_container)
    protected RelativeLayout logsContainer;

    @Nullable
    @BindView(R.id.tor_state)
    protected AppCompatTextView torState;

    @Nullable
    @BindView(R.id.snowflake_state)
    protected AppCompatTextView snowflakeState;

    @Nullable
    @BindView(R.id.connection_detail_logs)
    protected RecyclerView connectionDetailLogs;

    private TorLogAdapter torLogAdapter;

    @Nullable
    @BindView(R.id.progressbar)
    protected ProgressBar progressBar;

    @Nullable
    @BindView(R.id.progressbar_title)
    protected AppCompatTextView progressbarTitle;

    @Nullable
    @BindView(R.id.progressbar_description)
    protected AppCompatTextView progressbarDescription;

    //Only tablet layouts have guidelines as they are based on a ConstraintLayout
    @Nullable
    @BindView(R.id.guideline_top)
    protected Guideline guideline_top;

    @Nullable
    @BindView(R.id.guideline_bottom)
    protected Guideline guideline_bottom;

    @BindView(R.id.content)
    protected LinearLayout content;

    protected Provider provider;

    protected boolean isCompactLayout = false;
    protected boolean isActivityShowing;

    private float defaultGuidelineTopPercentage;
    private float defaultGuidelineBottomPercentage;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE);
        provider = getIntent().getParcelableExtra(PROVIDER_KEY);
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        initContentView();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initContentView();
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        initContentView();
    }

    private void initContentView() {
        if (provider != null) {
            setProviderHeaderText(provider.getName());
        }
        setProgressbarColorForPreLollipop();
        setDefaultGuidelineValues();
        setGlobalLayoutChangeListener();
    }

    private void setDefaultGuidelineValues() {
        if (isTabletLayout()) {
            defaultGuidelineTopPercentage = ((ConstraintLayout.LayoutParams) guideline_top.getLayoutParams()).guidePercent;
            defaultGuidelineBottomPercentage = ((ConstraintLayout.LayoutParams) guideline_bottom.getLayoutParams()).guidePercent;
        }
    }

    private void setProgressbarColorForPreLollipop() {
        if (progressBar == null || Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return;
        }
        progressBar.getIndeterminateDrawable().setColorFilter(
                ContextCompat.getColor(this, R.color.colorPrimary),
                PorterDuff.Mode.SRC_IN);
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (provider != null) {
            outState.putParcelable(PROVIDER_KEY, provider);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivityShowing = false;
        TorStatusObservable.getInstance().deleteObserver(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isActivityShowing = true;
        TorStatusObservable.getInstance().addObserver(this);
        setProgressbarDescription(getStringForCurrentStatus(this));
    }

    protected void restoreState(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.containsKey(PROVIDER_KEY)) {
            provider = savedInstanceState.getParcelable(PROVIDER_KEY);
        }
    }

    protected void setProviderHeaderLogo(@DrawableRes int providerHeaderLogo) {
        providerHeaderView.setLogo(providerHeaderLogo);
    }

    protected void setProviderHeaderText(String providerHeaderText) {
        providerHeaderView.setTitle(providerHeaderText);
    }

    protected void setProviderHeaderText(@StringRes int providerHeaderText) {
        providerHeaderView.setTitle(providerHeaderText);
    }

    protected void showConnectionDetails() {
        if (loadingScreen == null) {
            return;
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        connectionDetailLogs.setLayoutManager(layoutManager);
        connectionDetailLogs.addItemDecoration( new DividerItemDecoration(this, layoutManager.getOrientation()));
        torLogAdapter = new TorLogAdapter(getLastLogs());
        connectionDetailLogs.setAdapter(torLogAdapter);

        connectionDetailLogs.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState != SCROLL_STATE_IDLE) {
                    torLogAdapter.postponeUpdate = true;
                } else if (newState == SCROLL_STATE_IDLE && getFirstVisibleItemPosion() == 0) {
                    torLogAdapter.postponeUpdate = false;
                }
            }
        });

        snowflakeState.setText(getLastSnowflakeLog());
        torState.setText(getLastTorLog());
        connectionDetailBtn.setOnClickListener(v -> {
            connectionDetailBtn.setVisibility(GONE);
            logsContainer.setVisibility(VISIBLE);
        });
        connectionDetailContainer.setVisibility(VISIBLE);
    }

    private int getFirstVisibleItemPosion() {
        return ((LinearLayoutManager)connectionDetailLogs.getLayoutManager()).findFirstVisibleItemPosition();
    }

    protected void hideProgressBar() {
        if (loadingScreen == null) {
            return;
        }
        connectionDetailBtn.setVisibility(VISIBLE);
        connectionDetailContainer.setVisibility(GONE);
        logsContainer.setVisibility(GONE);
        loadingScreen.setVisibility(GONE);
        content.setVisibility(VISIBLE);
    }

    protected void showProgressBar() {
        if (loadingScreen == null) {
            return;
        }
        content.setVisibility(GONE);
        loadingScreen.setVisibility(VISIBLE);
    }

    protected void setProgressbarTitle(@StringRes int progressbarTitle) {
        if (loadingScreen == null) {
            return;
        }
        this.progressbarTitle.setText(progressbarTitle);
    }

    protected void setProgressbarDescription(String progressbarDescription) {
        if (loadingScreen == null) {
            return;
        }
        this.progressbarDescription.setText(progressbarDescription);
    }

    protected void setConfigProgress(int value) {
        if (loadingScreen == null) {
            return;
        }

        progressBar.setProgress(value, true);
        progressBar.setIndeterminate(value >= 100 || value < 0);
    }


    protected void showCompactLayout() {
        if (isCompactLayout) {
            return;
        }

        if (isTabletLayoutInLandscape() || isPhoneLayout()) {
            providerHeaderView.showCompactLayout();
        }

        showIncreasedTabletContentArea();
        isCompactLayout = true;
    }

    protected void showStandardLayout() {
        if (!isCompactLayout) {
            return;
        }
        providerHeaderView.showStandardLayout();
        showStandardTabletContentArea();
        isCompactLayout = false;
    }

    private boolean isTabletLayoutInLandscape() {
        // TabletLayout is based on a ConstraintLayout and uses Guidelines whereas the phone layout
        // has no such elements in it's layout xml file
        return  guideline_top != null &&
                guideline_bottom != null &&
                getResources().getConfiguration().orientation == ORIENTATION_LANDSCAPE;
    }

    protected boolean isPhoneLayout() {
        return guideline_top == null && guideline_bottom == null;
    }

    protected boolean isTabletLayout() {
        return guideline_top != null && guideline_bottom != null;
    }

    /**
     * Increases the white content area in tablet layouts
     */
    private void showIncreasedTabletContentArea() {
        if (isPhoneLayout()) {
            return;
        }
        ConstraintLayout.LayoutParams guideLineTopParams = (ConstraintLayout.LayoutParams) guideline_top.getLayoutParams();
        float increasedTopPercentage = defaultGuidelineTopPercentage - GUIDE_LINE_COMPACT_DELTA;
        guideLineTopParams.guidePercent = increasedTopPercentage > 0f ? increasedTopPercentage : 0f;
        guideline_top.setLayoutParams(guideLineTopParams);

        ConstraintLayout.LayoutParams guideLineBottomParams = (ConstraintLayout.LayoutParams) guideline_bottom.getLayoutParams();
        float increasedBottomPercentage = defaultGuidelineBottomPercentage + GUIDE_LINE_COMPACT_DELTA;
        guideLineBottomParams.guidePercent = increasedBottomPercentage < 1f ? increasedBottomPercentage : 1f;
        guideline_bottom.setLayoutParams(guideLineBottomParams);
    }

    /**
     * Restores the default size of the white content area in tablet layouts
     */
    private void showStandardTabletContentArea() {
        if (isPhoneLayout()) {
            return;
        }
        ConstraintLayout.LayoutParams guideLineTopParams = (ConstraintLayout.LayoutParams) guideline_top.getLayoutParams();
        guideLineTopParams.guidePercent = defaultGuidelineTopPercentage;
        guideline_top.setLayoutParams(guideLineTopParams);

        ConstraintLayout.LayoutParams guideLineBottomParams = (ConstraintLayout.LayoutParams) guideline_bottom.getLayoutParams();
        guideLineBottomParams.guidePercent = defaultGuidelineBottomPercentage;
        guideline_bottom.setLayoutParams(guideLineBottomParams);
    }

    /**
     * Checks if the keyboard is shown and switches between the standard layout and the compact layout
     */
    private void setGlobalLayoutChangeListener() {
        final View rootView = content.getRootView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //r will be populated with the coordinates of your view that area still visible.
                rootView.getWindowVisibleDisplayFrame(r);

                float deltaHiddenScreen =  1f - ((float) (r.bottom - r.top) / (float) rootView.getHeight());
                if (deltaHiddenScreen > 0.25f) {
                    // if more than 1/4 of the screen is hidden
                    showCompactLayout();
                } else {
                    showStandardLayout();
                }
            }
        });
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof TorStatusObservable) {
            runOnUiThread(() -> {
                if (TorStatusObservable.getStatus() != TorStatusObservable.TorStatus.OFF && loadingScreen != null) {
                    if (connectionDetailContainer.getVisibility() == GONE) {
                        showConnectionDetails();
                    } else {
                        setLogs(getLastTorLog(), getLastSnowflakeLog(), getLastLogs());
                    }
                }
                setProgressbarDescription(getStringForCurrentStatus(ConfigWizardBaseActivity.this));
                setConfigProgress(getBootstrapProgress());
            });
        }
    }

    protected void setLogs(String torLog, String snowflakeLog, List<String> lastLogs) {
        if (loadingScreen == null) {
            return;
        }
        torLogAdapter.updateData(lastLogs);
        torState.setText(torLog);
        snowflakeState.setText(snowflakeLog);
    }

    static class TorLogAdapter extends RecyclerView.Adapter<TorLogAdapter.ViewHolder> {
        private List<String> values;
        private boolean postponeUpdate;

        static class ViewHolder extends RecyclerView.ViewHolder {
            public AppCompatTextView logTextLabel;
            public View layout;

            public ViewHolder(View v) {
                super(v);
                layout = v;
                logTextLabel = v.findViewById(android.R.id.text1);
            }
        }

        public void updateData(List<String> data) {
            values = data;
            if (!postponeUpdate) {
                notifyDataSetChanged();
            }
        }

        public TorLogAdapter(List<String> data) {
            values = data;
        }

        @NonNull
        @Override
        public TorLogAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(
                    parent.getContext());
            View v = inflater.inflate(R.layout.v_log_item, parent, false);
            return new TorLogAdapter.ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(TorLogAdapter.ViewHolder holder, final int position) {
            final String log = values.get(position);
            holder.logTextLabel.setText(log);
        }

        @Override
        public int getItemCount() {
            return values.size();
        }
    }
}