-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOpeningHoursFragment.java
More file actions
3401 lines (3191 loc) · 166 KB
/
Copy pathOpeningHoursFragment.java
File metadata and controls
3401 lines (3191 loc) · 166 KB
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ch.poole.openinghoursfragment;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.ActionMenuView;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import ch.poole.android.rangebar.RangeBar;
import ch.poole.android.rangebar.RangeBar.PinTextFormatter;
import ch.poole.openinghoursfragment.pickers.DateRangePicker;
import ch.poole.openinghoursfragment.pickers.OccurrenceInMonthPicker;
import ch.poole.openinghoursfragment.pickers.RangePicker;
import ch.poole.openinghoursfragment.pickers.SetDateRangeListener;
import ch.poole.openinghoursfragment.pickers.SetRangeListener;
import ch.poole.openinghoursfragment.pickers.SetTimeRangeListener;
import ch.poole.openinghoursfragment.pickers.TimeRangePicker;
import ch.poole.openinghoursfragment.pickers.ValuePicker;
import ch.poole.openinghoursfragment.templates.TemplateDatabase;
import ch.poole.openinghoursfragment.templates.TemplateDatabaseHelper;
import ch.poole.openinghoursfragment.templates.TemplateDialog;
import ch.poole.openinghoursfragment.templates.TemplateMangementDialog;
import ch.poole.openinghoursfragment.templates.UpdateTextListener;
import ch.poole.openinghoursparser.DateRange;
import ch.poole.openinghoursparser.DateWithOffset;
import ch.poole.openinghoursparser.Event;
import ch.poole.openinghoursparser.Holiday;
import ch.poole.openinghoursparser.Holiday.Type;
import ch.poole.openinghoursparser.I18n;
import ch.poole.openinghoursparser.Month;
import ch.poole.openinghoursparser.Nth;
import ch.poole.openinghoursparser.OpeningHoursParseException;
import ch.poole.openinghoursparser.OpeningHoursParser;
import ch.poole.openinghoursparser.ParseException;
import ch.poole.openinghoursparser.Rule;
import ch.poole.openinghoursparser.RuleModifier;
import ch.poole.openinghoursparser.RuleModifier.Modifier;
import ch.poole.openinghoursparser.TimeSpan;
import ch.poole.openinghoursparser.Token;
import ch.poole.openinghoursparser.TokenMgrError;
import ch.poole.openinghoursparser.VarDate;
import ch.poole.openinghoursparser.VariableTime;
import ch.poole.openinghoursparser.WeekDay;
import ch.poole.openinghoursparser.WeekDayRange;
import ch.poole.openinghoursparser.WeekRange;
import ch.poole.openinghoursparser.YearRange;
/**
* DialogFragment that implements an editor for OpenStreetMap opening_hours tags
*
* @author Simon Poole
*
*/
public class OpeningHoursFragment extends DialogFragment implements SetDateRangeListener, SetRangeListener, SetTimeRangeListener, UpdateTextListener {
private static final String DEBUG_TAG = OpeningHoursFragment.class.getSimpleName();
private static final String VALUE_KEY = "value";
private static final String ORIGINAL_VALUE_KEY = "original_value";
private static final String KEY_KEY = "key";
private static final String REGION_KEY = "region";
private static final String OBJECT_KEY = "object";
private static final String STYLE_KEY = "style";
private static final String RULE_KEY = "rule";
private static final String SHOWTEMPLATES_KEY = "show_templates";
private static final String TEXTVALUES_KEY = "text_values";
private static final String FRAGMENT_KEY = "fragment";
private static final String LOCALE_KEY = "locale";
private static final String UNSUPPORTED_DATE = "Unsupported date ";
private static final String RULE_MISSING_FROM_LIST = "Rule missing from list!";
protected static final int OSM_MAX_TAG_LENGTH = 255;
private Context context = null;
private LayoutInflater inflater = null;
/**
* Saved state
*/
private ValueWithDescription key;
private String region;
private String object;
private String openingHoursValue;
private String originalOpeningHoursValue;
private int styleRes = 0;
private Locale locale;
/**
* If true we use a call back to the parent fragment
*/
private boolean useFragmentCallback;
private List<Rule> rules;
private AutoCompleteTextView text;
private LinearLayout errorMessages;
private OnSaveListener saveListener = null;
List<String> weekDays = WeekDay.nameValues();
List<String> months = Month.nameValues();
private boolean loadedDefault = false;
private boolean showTemplates = false;
private List<ValueWithDescription> textValues;
private OhTextWatcher watcher;
private TextTextWatcher textWatcher;
private Rebuilder rebuilder;
private AppCompatButton saveButton;
private View headerLine;
/**
* True if we encountered a parse error
*/
private boolean parseErrorFound;
/** record if we are not actually adding a OH value */
private boolean textMode = false;
static PinTextFormatter extendedTimeFormater = value -> {
int minutes = Integer.parseInt(value);
int tempMinutes = minutes - TimeSpan.MAX_TIME;
return String.format(Locale.US, "%02d", tempMinutes / 60) + ":" + String.format(Locale.US, "%02d", minutes % 60);
};
static PinTextFormatter timeFormater = value -> {
int minutes = Integer.parseInt(value);
return String.format(Locale.US, "%02d", minutes / 60) + ":" + String.format(Locale.US, "%02d", minutes % 60);
};
/**
* Create a new OpeningHoursFragment with callback to an activity
*
* @param key the key the OH values belongs to
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstance(@NonNull String key, @NonNull String value, int style, int rule) {
return newInstance(key, value, style, rule, false);
}
/**
* Create a new OpeningHoursFragment with callback to an activity
*
* @param key the key the OH values belongs to
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @param showTemplates if value is empty show the template selector instead of using a default when true
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstance(@NonNull String key, @NonNull String value, int style, int rule, boolean showTemplates) {
return newInstance(new ValueWithDescription(key, null), null, null, value, style, rule, showTemplates, null, null);
}
/**
* Create a new OpeningHoursFragment with callback to an activity
*
* @param key the key the OH values belongs to in an ValueWithDescription object
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @param showTemplates if value is empty show the template selector instead of using a default when true
* @param textValues for tags that can contain both OH and other values a list of possible non-OH values, or null
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstance(@NonNull ValueWithDescription key, @NonNull String value, int style, int rule, boolean showTemplates,
@Nullable ArrayList<ValueWithDescription> textValues) {
return newInstance(key, null, null, value, style, rule, showTemplates, textValues, null);
}
/**
* Create a new OpeningHoursFragment with callback to an activity
*
* @param key the key the OH values belongs to in an ValueWithDescription object
* @param region the current region
* @param object the object in question (typically the main osm tag)
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @param showTemplates if value is empty show the template selector instead of using a default when true
* @param textValues for tags that can contain both OH and other values a list of possible non-OH values, or null
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstance(@NonNull ValueWithDescription key, String region, String object, @NonNull String value, int style, int rule,
boolean showTemplates, @Nullable ArrayList<ValueWithDescription> textValues) {
return newInstance(key, region, object, value, style, rule, showTemplates, textValues, null);
}
/**
* Create a new OpeningHoursFragment with callback to an activity
*
* @param key the key the OH values belongs to in an ValueWithDescription object
* @param region the current region
* @param object the object in question (typically the main osm tag)
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @param showTemplates if value is empty show the template selector instead of using a default when true
* @param textValues for tags that can contain both OH and other values a list of possible non-OH values, or null
* @param locale if not null use a different Locale than the default for parser error messages
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstance(@NonNull ValueWithDescription key, String region, String object, @NonNull String value, int style, int rule,
boolean showTemplates, @Nullable ArrayList<ValueWithDescription> textValues, @Nullable Locale locale) {
OpeningHoursFragment f = new OpeningHoursFragment();
Bundle args = new Bundle();
args.putSerializable(KEY_KEY, key);
args.putString(REGION_KEY, region);
args.putString(OBJECT_KEY, object);
args.putSerializable(VALUE_KEY, value);
args.putInt(STYLE_KEY, style);
args.putInt(RULE_KEY, rule);
args.putBoolean(SHOWTEMPLATES_KEY, showTemplates);
args.putBoolean(FRAGMENT_KEY, false);
args.putSerializable(TEXTVALUES_KEY, textValues);
args.putSerializable(LOCALE_KEY, locale);
f.setArguments(args);
return f;
}
/**
* Create a new OpeningHoursFragment with callback to a fragment
*
* @param key the key the OH values belongs to
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstanceForFragment(@NonNull String key, @NonNull String value, int style, int rule) {
return newInstanceForFragment(key, value, style, rule, false);
}
/**
* Create a new OpeningHoursFragment with callback to a fragment
*
* @param key the key the OH values belongs to
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @param showTemplates if value is empty show the template selector instead of using a default when true
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstanceForFragment(@NonNull String key, @NonNull String value, int style, int rule, boolean showTemplates) {
return newInstanceForFragment(new ValueWithDescription(key, null), null, null, value, style, rule, showTemplates, null, null);
}
/**
* Create a new OpeningHoursFragment with callback to a fragment
*
* @param key the key the OH values belongs to in an ValueWithDescription object
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @param showTemplates if value is empty show the template selector instead of using a default when true
* @param textValues for tags that can contain both OH and other values a list of possible non-OH values, or null
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstanceForFragment(@NonNull ValueWithDescription key, @NonNull String value, int style, int rule,
boolean showTemplates, @Nullable ArrayList<ValueWithDescription> textValues) {
return newInstanceForFragment(key, null, null, value, style, rule, showTemplates, textValues, null);
}
/**
* Create a new OpeningHoursFragment with callback to a fragment
*
* @param key the key the OH values belongs to in an ValueWithDescription object
* @param region the current region
* @param object the object in question (typically the main osm tag)
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @param showTemplates if value is empty show the template selector instead of using a default when true
* @param textValues for tags that can contain both OH and other values a list of possible non-OH values, or null
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstanceForFragment(@NonNull ValueWithDescription key, String region, String object, @NonNull String value, int style,
int rule, boolean showTemplates, @Nullable ArrayList<ValueWithDescription> textValues) {
return newInstanceForFragment(key, region, object, value, style, rule, showTemplates, textValues, null);
}
/**
* Create a new OpeningHoursFragment with callback to a fragment
*
* @param key the key the OH values belongs to in an ValueWithDescription object
* @param region the current region
* @param object the object in question (typically the main osm tag)
* @param value the OH value
* @param style resource id for the Android style to use
* @param rule rule to scroll to or -1 (currently ignored)
* @param showTemplates if value is empty show the template selector instead of using a default when true
* @param textValues for tags that can contain both OH and other values a list of possible non-OH values, or null
* @param locale if not null use a different Locale than the default for parser error messages
* @return an OpeningHoursFragment
*/
public static OpeningHoursFragment newInstanceForFragment(@NonNull ValueWithDescription key, @Nullable String region, @Nullable String object,
@NonNull String value, int style, int rule, boolean showTemplates, @Nullable ArrayList<ValueWithDescription> textValues, @Nullable Locale locale) {
OpeningHoursFragment f = new OpeningHoursFragment();
Bundle args = new Bundle();
args.putSerializable(KEY_KEY, key);
args.putString(REGION_KEY, region);
args.putString(OBJECT_KEY, object);
args.putSerializable(VALUE_KEY, value);
args.putInt(STYLE_KEY, style);
args.putInt(RULE_KEY, rule);
args.putBoolean(SHOWTEMPLATES_KEY, showTemplates);
args.putBoolean(FRAGMENT_KEY, true);
args.putSerializable(TEXTVALUES_KEY, textValues);
args.putSerializable(LOCALE_KEY, locale);
f.setArguments(args);
return f;
}
@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
@SuppressWarnings("unchecked")
@SuppressLint("InflateParams")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(DEBUG_TAG, "onCreateView");
int initialRule = -1;
if (savedInstanceState != null) {
Log.d(DEBUG_TAG, "Restoring from saved state");
getStateFromBundle(savedInstanceState);
} else {
final Bundle arguments = getArguments();
getStateFromBundle(arguments);
initialRule = arguments.getInt(RULE_KEY);
showTemplates = arguments.getBoolean(SHOWTEMPLATES_KEY);
originalOpeningHoursValue = arguments.getString(VALUE_KEY);
}
if (styleRes == 0) {
styleRes = R.style.Theme_AlertDialog; // fallback
}
if (openingHoursValue == null || "".equals(openingHoursValue)) {
if (!showTemplates) {
loadDefault();
loadedDefault = openingHoursValue != null;
}
}
context = new ContextThemeWrapper(getActivity(), styleRes);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final LinearLayout openingHoursLayout = (LinearLayout) inflater.inflate(R.layout.openinghours, null);
final ScrollView sv = (ScrollView) openingHoursLayout.findViewById(R.id.openinghours_view);
text = (AutoCompleteTextView) openingHoursLayout.findViewById(R.id.openinghours_string_edit);
watcher = new OhTextWatcher(sv);
textWatcher = new TextTextWatcher();
rebuilder = new Rebuilder(sv);
// set parser locale singleton
I18n.setLocale(locale != null ? locale : Locale.getDefault());
final View modeContainer = openingHoursLayout.findViewById(R.id.modeContainer);
headerLine = openingHoursLayout.findViewById(R.id.headerLine);
errorMessages = (LinearLayout) openingHoursLayout.findViewById(R.id.openinghours_error_messages);
// check if this is a mixed value tag
final boolean hasTextValues = textValues != null;
textMode = hasTextValues
&& (textValues.contains(new ValueWithDescription(openingHoursValue, null)) || openingHoursValue == null || "".equals(openingHoursValue));
buildLayout(openingHoursLayout, openingHoursValue == null ? "" : openingHoursValue, initialRule);
if (hasTextValues) {
final RadioGroup modeGroup = (RadioGroup) openingHoursLayout.findViewById(R.id.modeGroup);
final RadioButton useOH = (RadioButton) modeGroup.findViewById(R.id.use_oh);
final RadioButton useText = (RadioButton) modeGroup.findViewById(R.id.use_text);
if (textMode) {
useText.setChecked(true);
setUpTextMode();
} else {
useOH.setChecked(true);
rebuilder.rebuild();
}
modeGroup.setOnCheckedChangeListener((group, checkedId) -> {
openingHoursValue = text.getText().toString();
removeHighlight(text);
errorMessages.removeAllViews();
removeWatchers();
final View fab = openingHoursLayout.findViewById(R.id.more);
if (checkedId == useText.getId()) {
textMode = true;
buildLayout(openingHoursLayout, openingHoursValue, -1);
fab.setVisibility(View.GONE);
setUpTextMode();
} else if (checkedId == useOH.getId()) {
textMode = false;
text.setText(openingHoursValue);
rebuilder.rebuild();
fab.setVisibility(View.VISIBLE);
setUpOHMode();
}
});
modeContainer.setVisibility(View.VISIBLE);
} else {
modeContainer.setVisibility(View.GONE);
rebuilder.rebuild();
}
// add callbacks for the buttons
View cancel = openingHoursLayout.findViewById(R.id.cancel);
cancel.setOnClickListener(v -> dismiss());
Object listener = null;
try {
if (useFragmentCallback) {
listener = getParentFragment();
// we may be nested one or two levels deep
if (!(listener instanceof OnSaveListener)) {
listener = ((Fragment) listener).getParentFragment();
}
} else {
listener = getContext();
}
saveListener = (OnSaveListener) listener;
} catch (ClassCastException e) {
throw new ClassCastException(
listener != null ? listener.getClass().getCanonicalName() + " must implement OnSaveListener" : "OnSaveListener is null");
}
saveButton = (AppCompatButton) openingHoursLayout.findViewById(R.id.save);
enableSaveButton(openingHoursValue);
saveButton.setOnClickListener(v -> {
saveListener.save(key.getValue(), text.getText().toString());
dismiss();
});
return openingHoursLayout;
}
/**
* Remove watchers on the EditText
*/
private void removeWatchers() {
text.removeTextChangedListener(watcher);
text.removeTextChangedListener(textWatcher);
}
/**
* Get state/arguments from a bundle
*
* @param bundle the Bundle
*/
private void getStateFromBundle(@NonNull Bundle bundle) {
key = (ValueWithDescription) bundle.getSerializable(KEY_KEY);
region = bundle.getString(REGION_KEY);
object = bundle.getString(OBJECT_KEY);
openingHoursValue = bundle.getString(VALUE_KEY);
originalOpeningHoursValue = bundle.getString(ORIGINAL_VALUE_KEY);
styleRes = bundle.getInt(STYLE_KEY);
useFragmentCallback = bundle.getBoolean(FRAGMENT_KEY);
textValues = (List<ValueWithDescription>) bundle.getSerializable(TEXTVALUES_KEY);
locale = (Locale) bundle.getSerializable(LOCALE_KEY);
}
/**
* Setup listeners for text mode
*/
private void setUpTextMode() {
text.removeCallbacks(updateStringRunnable);
headerLine.setVisibility(View.VISIBLE);
text.setOnEditorActionListener(null);
removeWatchers();
text.addTextChangedListener(textWatcher);
}
/**
* Setup listeners for OH mode
*/
private void setUpOHMode() {
text.removeCallbacks(updateStringRunnable);
text.setAdapter(null);
text.setOnClickListener(null);
headerLine.setVisibility(View.GONE);
text.setOnEditorActionListener(editorActionListener);
removeWatchers();
text.addTextChangedListener(watcher);
}
/**
* Try to locate a reasonable default value
*/
private void loadDefault() {
TemplateDatabaseHelper helper = new TemplateDatabaseHelper(getContext());
try (SQLiteDatabase mDatabase = helper.getReadableDatabase()) {
String[][] values = new String[][] { { region, object }, { null, object }, { region, null } };
for (String[] v : values) {
openingHoursValue = TemplateDatabase.getDefault(mDatabase, key.getValue(), v[0], v[1]);
if (openingHoursValue != null) {
return;
}
}
openingHoursValue = TemplateDatabase.getDefault(mDatabase, null, null, null);
} finally {
helper.close();
}
}
@Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null) {
final Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, window.getAttributes().height);
}
}
/**
* Enable the save button if the text has changed
*
* @author simon
*
*/
private final class TextTextWatcher extends DefaultTextWatcher {
@Override
public void afterTextChanged(Editable s) {
enableSaveButton(text.getText().toString());
}
}
/**
* Re-parses and rebuilds the form if the text is changed by typing
*
* @author simon
*
*/
private class OhTextWatcher extends DefaultTextWatcher {
final ScrollView scrollView;
/**
* Construct a new instance
*
* @param scrollView the ScrollView holding the bits that we will want to update
*/
OhTextWatcher(@NonNull ScrollView scrollView) {
this.scrollView = scrollView;
}
@Override
public void afterTextChanged(Editable s) {
Runnable watcherRunnable = () -> {
text.removeTextChangedListener(watcher);
String textString = text.getText().toString();
OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(textString.getBytes()));
try {
rules = parser.rules(false);
if (text.getText() instanceof Spannable) {
int currentPos = text.getSelectionStart();
text.setText(textString);
text.setSelection(currentPos);
}
errorMessages.removeAllViews();
TextView message = new TextView(getContext());
message.setSingleLine();
message.setText(R.string.spd_ohf_update_hint);
errorMessages.addView(message);
} catch (OpeningHoursParseException pex) {
displayParseErrors(pex);
} catch (TokenMgrError err) {
// we currently can't do anything reasonable here except ignore
Log.e(DEBUG_TAG, err.getMessage());
}
enableSaveButton(text.getText().toString());
text.addTextChangedListener(watcher);
};
text.removeCallbacks(watcherRunnable);
text.postDelayed(watcherRunnable, 100); // a direct post currently doesn't work
}
}
private class Rebuilder {
final ScrollView scrollView;
/**
* Construct a new instance
*
* @param scrollView the ScrollView holding the bits that we will want to update
*/
Rebuilder(@NonNull ScrollView scrollView) {
this.scrollView = scrollView;
}
/**
* Actually rebuild
*/
private void rebuild() {
Runnable rebuildRunnable = () -> {
text.removeTextChangedListener(watcher);
OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(text.getText().toString().getBytes()));
try {
rules = parser.rules(false);
buildForm(scrollView, rules);
removeHighlight(text);
errorMessages.removeAllViews();
} catch (OpeningHoursParseException pex) {
displayParseErrors(pex);
} catch (TokenMgrError err) {
// we currently can't do anything reasonable here except ignore
Log.e(DEBUG_TAG, err.getMessage());
}
enableSaveButton(text.getText().toString());
text.addTextChangedListener(watcher);
};
text.removeCallbacks(rebuildRunnable);
text.postDelayed(rebuildRunnable, 100); // a direct post currently doesn't work
}
}
/**
* Display any parse errors
*
* @param pex a parse exceptions
*/
private void displayParseErrors(@NonNull OpeningHoursParseException pex) {
Log.d(DEBUG_TAG, pex.getMessage());
highlightParseError(text, pex);
errorMessages.removeAllViews();
for (OpeningHoursParseException ex : pex.getExceptions()) {
TextView message = new TextView(getContext());
message.setSingleLine();
message.setText(ex.getMessage());
message.setTextColor(ContextCompat.getColor(getContext(), R.color.error_text));
final int column = Math.min(ex.getColumn() + 1, message.length() - 1);
message.setOnClickListener(v -> text.setSelection(column, column));
errorMessages.addView(message);
}
}
private OnClickListener autocompleteOnClick = v -> {
if (v.hasFocus()) {
((AutoCompleteTextView) v).showDropDown();
}
};
private OnEditorActionListener editorActionListener = (TextView view, int actionId, KeyEvent event) -> {
if (actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE
|| (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
rebuilder.rebuild();
}
return true;
};
/**
* Build the parts of the layout that only need to be done once
*
* @param openingHoursLayout the layout
* @param openingHoursValue the OH value
* @param initialRule index of the rule to scroll to, currently ignored
* @return a ScrollView
*/
@Nullable
private ScrollView buildLayout(final @NonNull LinearLayout openingHoursLayout, @NonNull String openingHoursValue, final int initialRule) {
final ScrollView sv = (ScrollView) openingHoursLayout.findViewById(R.id.openinghours_view);
if (text == null || sv == null) {
Log.e(DEBUG_TAG, "ScrollView or EditText not found");
return null;
}
String keyDescription = key.getDescription();
if (keyDescription != null && !"".equals(keyDescription)) {
text.setHint(keyDescription);
}
sv.removeAllViews();
final FloatingActionButton fab = (FloatingActionButton) openingHoursLayout.findViewById(R.id.more);
// non-OH support
if (textValues != null) {
final RadioGroup modeGroup = (RadioGroup) openingHoursLayout.findViewById(R.id.modeGroup);
final RadioButton useText = (RadioButton) modeGroup.findViewById(R.id.use_text);
if (textMode) {
ValueArrayAdapter adapter = new ValueArrayAdapter(getContext(), android.R.layout.simple_spinner_item, textValues);
text.setAdapter(adapter);
text.setOnClickListener(autocompleteOnClick);
text.setOnItemClickListener((parent, view, position, id) -> {
Object o = parent.getItemAtPosition(position);
if (o instanceof ValueWithDescription) {
text.setText(((ValueWithDescription) o).getValue());
} else if (o instanceof String) {
text.setText((String) o);
}
});
text.setText(openingHoursValue);
setUpTextMode();
fab.setVisibility(View.GONE);
setupFab(sv, fab);
return sv;
} else {
setUpOHMode();
if ("".equals(openingHoursValue)) {
if (!showTemplates) {
loadDefault();
if (!"".equals(openingHoursValue)) {
ch.poole.openinghoursfragment.Util.toastTop(getActivity(), getString(R.string.loaded_default));
}
} else {
showTemplates = false;
TemplateMangementDialog.showDialog(this, false, key, null, null, text.getText().toString(), styleRes);
}
}
}
} else {
setUpOHMode();
}
textMode = false;
text.setText(openingHoursValue);
fab.setVisibility(View.VISIBLE);
OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(openingHoursValue.getBytes()));
try {
rules = parser.rules(false);
buildForm(sv, rules);
removeHighlight(text);
} catch (OpeningHoursParseException pex) {
Log.d(DEBUG_TAG, pex.getMessage());
highlightParseError(text, pex);
} catch (TokenMgrError err) {
// we currently can't do anything reasonable here except ignore
Log.e(DEBUG_TAG, err.getMessage());
}
setupFab(sv, fab);
return sv;
}
/**
* Configure the FAB
*
* @param sv the main ScrollView
* @param fab the FAB
*/
private void setupFab(@NonNull ScrollView sv, @NonNull FloatingActionButton fab) {
class AddRuleListener implements OnMenuItemClickListener {
String ruleString;
/**
* Construct a new listener for creating Rules
*
* @param rule a String containing a rule
*/
AddRuleListener(@NonNull String rule) {
ruleString = rule;
}
@Override
public boolean onMenuItemClick(MenuItem item) { // NOSONAR
OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(ruleString.getBytes()));
List<Rule> rules2 = null;
try {
rules2 = parser.rules(false);
} catch (ParseException pex) {
Log.e(DEBUG_TAG, pex.getMessage());
} catch (TokenMgrError err) {
Log.e(DEBUG_TAG, err.getMessage());
}
if (rules2 != null && !rules2.isEmpty()) {
if (rules == null || hasParseError()) { // if there was an unparseable string it needs to be
// fixed first
ch.poole.openinghoursfragment.Util.toastTop(getActivity(), R.string.would_overwrite_invalid_value);
return true;
}
rules.add(rules2.get(0));
updateString();
rebuilder.rebuild(); // hack to force rebuild of form
// scroll to bottom
text.postDelayed(() -> ch.poole.openinghoursfragment.Util.scrollToRow(sv, null, false, false), 200);
}
return true;
}
}
fab.setOnClickListener(v -> {
PopupMenu popup = new PopupMenu(context, fab);
// menu items for adding rules
MenuItem addRule = popup.getMenu().add(R.string.add_rule);
addRule.setOnMenuItemClickListener(new AddRuleListener("Mo 6:00-20:00"));
MenuItem addRulePH = popup.getMenu().add(R.string.add_rule_closed_on_holidays);
addRulePH.setOnMenuItemClickListener(new AddRuleListener("PH closed"));
MenuItem addRule247 = popup.getMenu().add(R.string.add_rule_247);
addRule247.setOnMenuItemClickListener(new AddRuleListener("24/7"));
MenuItem loadTemplate = popup.getMenu().add(R.string.load_template);
loadTemplate.setOnMenuItemClickListener(item -> {
TemplateMangementDialog.showDialog(OpeningHoursFragment.this, false, key, region, object, text.getText().toString(), styleRes);
return true;
});
MenuItem saveTemplate = popup.getMenu().add(R.string.save_to_template);
saveTemplate.setOnMenuItemClickListener(item -> {
TemplateDialog.showDialog(OpeningHoursFragment.this, text.getText().toString(), key, false, -1, styleRes);
return true;
});
MenuItem manageTemplate = popup.getMenu().add(R.string.manage_templates);
manageTemplate.setOnMenuItemClickListener(item -> {
TemplateMangementDialog.showDialog(OpeningHoursFragment.this, true, key, region, object, text.getText().toString(), styleRes);
return true;
});
MenuItem refresh = popup.getMenu().add(R.string.refresh);
refresh.setOnMenuItemClickListener(item -> {
updateString();
rebuilder.rebuild(); // hack to force rebuild of form
return true;
});
MenuItem clear = popup.getMenu().add(R.string.clear);
clear.setOnMenuItemClickListener(item -> {
if (rules != null) { // FIXME should likely disable the entry if there is actually nothing to
// clear
rules.clear();
updateString();
} else {
text.setText("");
}
rebuilder.rebuild();
return true;
});
popup.show();// showing popup menu
});
}
/**
* Check if we have an parser error
*
* @return true if there was a parser error
*/
public boolean hasParseError() {
return parseErrorFound;
}
/**
* Highlight the position of a parse error
*
* Side effect sets parserErrorFound to true
*
* @param text he EditText the string is displayed in
* @param pex the ParseException to use
*/
private void highlightParseError(@NonNull EditText text, @NonNull OpeningHoursParseException ohpex) {
parseErrorFound = true;
int currentPos = text.getSelectionStart();
Spannable spannable = new SpannableString(text.getText());
boolean first = true;
for (OpeningHoursParseException pex : ohpex.getExceptions()) {
Token current = pex.currentToken;
if (current == null || current.next == null) {
continue;
}
int c = current.next.beginColumn - 1; // starts at 1
spannable.setSpan(new ForegroundColorSpan(Color.RED), c, Math.max(c, Math.min(c + 1, spannable.length())), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (first) {
first = false;
}
}
text.setText(spannable, TextView.BufferType.SPANNABLE);
text.setSelection(currentPos);
}
/**
* Remove all parse error highlighting
*
* Side effect sets parserErrorFound to false
*
* @param text the EditText the string is displayed in
*/
private void removeHighlight(@NonNull EditText text) {
parseErrorFound = false;
int pos = text.getSelectionStart();
int prevLen = text.length();
if (rules != null) {
String t = ch.poole.openinghoursparser.Util.rulesToOpeningHoursString(rules);
text.setText(t);
}
text.setSelection(prevLen < text.length() ? text.length() : Math.min(pos, text.length()));
}
/**
* (Re-)Build the contents of the scroll view
*
* @param sv the ScrollView
* @param rules List of Rules to display
*/
private synchronized void buildForm(@NonNull ScrollView sv, @NonNull List<Rule> rules) {
sv.removeAllViews();
LinearLayout ll = new LinearLayout(getActivity());
ll.setPadding(0, 0, 0, dpToPixels(64));
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
addRules(false, rules, ll);
}
/**
* Loop over the list of rules adding views and menus for the entries
*
* @param groupMode use groupMode, currently ignored
* @param rules List of Rules to display
* @param ll layout to add the wules to
*/
private void addRules(boolean groupMode, @NonNull final List<Rule> rules, @NonNull LinearLayout ll) {
boolean first = true;
int headerCount = 1;
for (final Rule r : rules) {
if (first) { // everything except days and times should be
// the same and only needs to be displayed
// once in groupMode, in normal mode this is
// always true
final LinearLayout groupHeader = (LinearLayout) inflater.inflate(R.layout.rule_header, null);
TextView header = (TextView) groupHeader.findViewById(R.id.header);
header.setText(getActivity().getString(groupMode ? R.string.group_header : R.string.rule_header, headerCount));
RadioButton normal = (RadioButton) groupHeader.findViewById(R.id.normal_rule);
if (!r.isAdditive() && !r.isFallBack()) {
normal.setChecked(true);
}
normal.setOnClickListener(v -> {
RadioButton rb = (RadioButton) v;
if (rb.isChecked()) {
r.setFallBack(false);
r.setAdditive(false);
updateString();
rebuilder.rebuild();
}
});
RadioButton additive = (RadioButton) groupHeader.findViewById(R.id.additive_rule);
if (r.isAdditive()) {
additive.setChecked(true);