-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathEventActivity.kt
More file actions
2466 lines (2179 loc) · 90.5 KB
/
EventActivity.kt
File metadata and controls
2466 lines (2179 loc) · 90.5 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 org.fossify.calendar.activities
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.CalendarContract.Attendees
import android.provider.CalendarContract.Colors
import android.provider.CalendarContract.Events
import android.provider.ContactsContract.CommonDataKinds
import android.provider.ContactsContract.CommonDataKinds.StructuredName
import android.provider.ContactsContract.Data
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.core.graphics.drawable.toDrawable
import androidx.core.net.toUri
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.MaterialTimePicker.INPUT_MODE_CLOCK
import com.google.android.material.timepicker.TimeFormat
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.fossify.calendar.R
import org.fossify.calendar.adapters.AutoCompleteTextViewAdapter
import org.fossify.calendar.databinding.ActivityEventBinding
import org.fossify.calendar.databinding.ItemAttendeeBinding
import org.fossify.calendar.dialogs.DeleteEventDialog
import org.fossify.calendar.dialogs.EditRepeatingEventDialog
import org.fossify.calendar.dialogs.ReminderWarningDialog
import org.fossify.calendar.dialogs.RepeatLimitTypePickerDialog
import org.fossify.calendar.dialogs.RepeatRuleWeeklyDialog
import org.fossify.calendar.dialogs.SelectCalendarDialog
import org.fossify.calendar.dialogs.SelectEventColorDialog
import org.fossify.calendar.extensions.calDAVHelper
import org.fossify.calendar.extensions.calendarsDB
import org.fossify.calendar.extensions.cancelNotification
import org.fossify.calendar.extensions.config
import org.fossify.calendar.extensions.eventsDB
import org.fossify.calendar.extensions.eventsHelper
import org.fossify.calendar.extensions.getNewEventTimestampFromCode
import org.fossify.calendar.extensions.getRepetitionText
import org.fossify.calendar.extensions.getShortDaysFromBitmask
import org.fossify.calendar.extensions.isXMonthlyRepetition
import org.fossify.calendar.extensions.isXWeeklyRepetition
import org.fossify.calendar.extensions.isXYearlyRepetition
import org.fossify.calendar.extensions.notifyEvent
import org.fossify.calendar.extensions.seconds
import org.fossify.calendar.extensions.shareEvents
import org.fossify.calendar.extensions.showEventRepeatIntervalDialog
import org.fossify.calendar.helpers.ATTENDEES
import org.fossify.calendar.helpers.AVAILABILITY
import org.fossify.calendar.helpers.CALDAV
import org.fossify.calendar.helpers.CALENDAR_ID
import org.fossify.calendar.helpers.CLASS
import org.fossify.calendar.helpers.CURRENT_TIME_ZONE
import org.fossify.calendar.helpers.DELETE_ALL_OCCURRENCES
import org.fossify.calendar.helpers.DELETE_FUTURE_OCCURRENCES
import org.fossify.calendar.helpers.DELETE_SELECTED_OCCURRENCE
import org.fossify.calendar.helpers.EDIT_ALL_OCCURRENCES
import org.fossify.calendar.helpers.EDIT_FUTURE_OCCURRENCES
import org.fossify.calendar.helpers.EDIT_SELECTED_OCCURRENCE
import org.fossify.calendar.helpers.END_TS
import org.fossify.calendar.helpers.EVENT
import org.fossify.calendar.helpers.EVENT_CALENDAR_ID
import org.fossify.calendar.helpers.EVENT_COLOR
import org.fossify.calendar.helpers.EVENT_ID
import org.fossify.calendar.helpers.EVENT_OCCURRENCE_TS
import org.fossify.calendar.helpers.FLAG_ALL_DAY
import org.fossify.calendar.helpers.Formatter
import org.fossify.calendar.helpers.IS_DUPLICATE_INTENT
import org.fossify.calendar.helpers.IS_NEW_EVENT
import org.fossify.calendar.helpers.LOCAL_CALENDAR_ID
import org.fossify.calendar.helpers.NEW_EVENT_SET_HOUR_DURATION
import org.fossify.calendar.helpers.NEW_EVENT_START_TS
import org.fossify.calendar.helpers.ORIGINAL_ATTENDEES
import org.fossify.calendar.helpers.ORIGINAL_END_TS
import org.fossify.calendar.helpers.ORIGINAL_START_TS
import org.fossify.calendar.helpers.REMINDER_1_MINUTES
import org.fossify.calendar.helpers.REMINDER_1_TYPE
import org.fossify.calendar.helpers.REMINDER_2_MINUTES
import org.fossify.calendar.helpers.REMINDER_2_TYPE
import org.fossify.calendar.helpers.REMINDER_3_MINUTES
import org.fossify.calendar.helpers.REMINDER_3_TYPE
import org.fossify.calendar.helpers.REMINDER_EMAIL
import org.fossify.calendar.helpers.REMINDER_NOTIFICATION
import org.fossify.calendar.helpers.REMINDER_OFF
import org.fossify.calendar.helpers.REPEAT_INTERVAL
import org.fossify.calendar.helpers.REPEAT_LAST_DAY
import org.fossify.calendar.helpers.REPEAT_LIMIT
import org.fossify.calendar.helpers.REPEAT_ORDER_WEEKDAY
import org.fossify.calendar.helpers.REPEAT_ORDER_WEEKDAY_USE_LAST
import org.fossify.calendar.helpers.REPEAT_RULE
import org.fossify.calendar.helpers.REPEAT_SAME_DAY
import org.fossify.calendar.helpers.SOURCE_IMPORTED_ICS
import org.fossify.calendar.helpers.SOURCE_SIMPLE_CALENDAR
import org.fossify.calendar.helpers.START_TS
import org.fossify.calendar.helpers.STATUS
import org.fossify.calendar.helpers.STORED_LOCALLY_ONLY
import org.fossify.calendar.helpers.TIME_ZONE
import org.fossify.calendar.helpers.generateImportId
import org.fossify.calendar.models.Attendee
import org.fossify.calendar.models.CalendarEntity
import org.fossify.calendar.models.Event
import org.fossify.calendar.models.MyTimeZone
import org.fossify.calendar.models.Reminder
import org.fossify.commons.dialogs.ColorPickerDialog
import org.fossify.commons.dialogs.ConfirmationAdvancedDialog
import org.fossify.commons.dialogs.PermissionRequiredDialog
import org.fossify.commons.dialogs.RadioGroupDialog
import org.fossify.commons.extensions.addBitIf
import org.fossify.commons.extensions.applyColorFilter
import org.fossify.commons.extensions.beGone
import org.fossify.commons.extensions.beGoneIf
import org.fossify.commons.extensions.beVisible
import org.fossify.commons.extensions.beVisibleIf
import org.fossify.commons.extensions.checkAppSideloading
import org.fossify.commons.extensions.getColoredDrawableWithColor
import org.fossify.commons.extensions.getDatePickerDialogTheme
import org.fossify.commons.extensions.getFormattedMinutes
import org.fossify.commons.extensions.getIntValue
import org.fossify.commons.extensions.getProperBackgroundColor
import org.fossify.commons.extensions.getProperPrimaryColor
import org.fossify.commons.extensions.getProperTextColor
import org.fossify.commons.extensions.getStringValue
import org.fossify.commons.extensions.getTimePickerDialogTheme
import org.fossify.commons.extensions.hasPermission
import org.fossify.commons.extensions.hideKeyboard
import org.fossify.commons.extensions.isDynamicTheme
import org.fossify.commons.extensions.isGone
import org.fossify.commons.extensions.isVisible
import org.fossify.commons.extensions.launchActivityIntent
import org.fossify.commons.extensions.onGlobalLayout
import org.fossify.commons.extensions.onTextChangeListener
import org.fossify.commons.extensions.openNotificationSettings
import org.fossify.commons.extensions.queryCursor
import org.fossify.commons.extensions.setFillWithStroke
import org.fossify.commons.extensions.showErrorToast
import org.fossify.commons.extensions.showPickSecondsDialogHelper
import org.fossify.commons.extensions.toast
import org.fossify.commons.extensions.updateTextColors
import org.fossify.commons.extensions.value
import org.fossify.commons.extensions.viewBinding
import org.fossify.commons.helpers.EVERY_DAY_BIT
import org.fossify.commons.helpers.FRIDAY_BIT
import org.fossify.commons.helpers.MONDAY_BIT
import org.fossify.commons.helpers.NavigationIcon
import org.fossify.commons.helpers.PERMISSION_READ_CONTACTS
import org.fossify.commons.helpers.SATURDAY_BIT
import org.fossify.commons.helpers.SAVE_DISCARD_PROMPT_INTERVAL
import org.fossify.commons.helpers.SUNDAY_BIT
import org.fossify.commons.helpers.SimpleContactsHelper
import org.fossify.commons.helpers.THURSDAY_BIT
import org.fossify.commons.helpers.TUESDAY_BIT
import org.fossify.commons.helpers.WEDNESDAY_BIT
import org.fossify.commons.helpers.ensureBackgroundThread
import org.fossify.commons.helpers.getJavaDayOfWeekFromISO
import org.fossify.commons.models.RadioItem
import org.fossify.commons.views.MyAutoCompleteTextView
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.util.TimeZone
import java.util.regex.Pattern
class EventActivity : SimpleActivity() {
private val LAT_LON_PATTERN =
"^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)([,;])\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)\$"
private val SELECT_TIME_ZONE_INTENT = 1
private var mIsAllDayEvent = false
private var mReminder1Minutes = REMINDER_OFF
private var mReminder2Minutes = REMINDER_OFF
private var mReminder3Minutes = REMINDER_OFF
private var mReminder1Type = REMINDER_NOTIFICATION
private var mReminder2Type = REMINDER_NOTIFICATION
private var mReminder3Type = REMINDER_NOTIFICATION
private var mRepeatInterval = 0
private var mRepeatLimit = 0L
private var mRepeatRule = 0
private var mCalendarId = LOCAL_CALENDAR_ID
private var mEventOccurrenceTS = 0L
private var mLastSavePromptTS = 0L
private var mEventCalendarId = STORED_LOCALLY_ONLY
private var mWasContactsPermissionChecked = false
private var mWasCalendarChanged = false
private var mAttendees = ArrayList<Attendee>()
private var mOriginalAttendees = ArrayList<Attendee>()
private var mAttendeeAutoCompleteViews = ArrayList<MyAutoCompleteTextView>()
private var mAvailableContacts = ArrayList<Attendee>()
private var mSelectedContacts = ArrayList<Attendee>()
private var mAvailability = Attendees.AVAILABILITY_BUSY
private var mAccessLevel = Events.ACCESS_DEFAULT
private var mStatus = Events.STATUS_CONFIRMED
private var mStoredCalendars = ArrayList<CalendarEntity>()
private var mOriginalTimeZone = DateTimeZone.getDefault().id
private var mOriginalStartTS = 0L
private var mOriginalEndTS = 0L
private var mIsNewEvent = true
private var mEventColor = 0
private var mConvertedFromOriginalAllDay = false
private lateinit var mEventStartDateTime: DateTime
private lateinit var mEventEndDateTime: DateTime
private lateinit var mEvent: Event
private val binding by viewBinding(ActivityEventBinding::inflate)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupOptionsMenu()
refreshMenuItems()
if (checkAppSideloading()) {
return
}
setupEdgeToEdge(padBottomImeAndSystem = listOf(binding.eventNestedScrollview))
setupMaterialScrollListener(binding.eventNestedScrollview, binding.eventAppbar)
val intent = intent ?: return
mWasContactsPermissionChecked = hasPermission(PERMISSION_READ_CONTACTS)
val eventId = intent.getLongExtra(EVENT_ID, 0L)
ensureBackgroundThread {
val locations = eventsDB.getAllLocations()
val eventTitleMap = eventsDB.getAllEvents()
.associateBy { it.title } as HashMap<String, Event>
binding.eventTitle.setOnItemClickListener { parent, view, position, id ->
val prev = eventTitleMap[parent.getItemAtPosition(position)]
binding.eventLocation.setText(prev!!.location)
binding.eventDescription.setText(prev.description)
binding.eventAllDay.isChecked = prev.getIsAllDay()
mEventEndDateTime = mEventStartDateTime.plus(1000L * (prev.endTS - prev.startTS))
mReminder1Minutes = prev.reminder1Minutes
mReminder2Minutes = prev.reminder2Minutes
mReminder3Minutes = prev.reminder3Minutes
mReminder1Type = prev.reminder1Type
mReminder2Type = prev.reminder2Type
mReminder3Type = prev.reminder3Type
mAccessLevel = prev.accessLevel
mAvailability = prev.availability
mStatus = prev.status
mEventColor = prev.color
mAttendees = prev.attendees as ArrayList<Attendee>
mCalendarId = prev.calendarId
checkRepeatTexts(mRepeatInterval)
checkRepeatRule()
updateTexts()
updateCalendar()
checkAttendees()
updateActionBarTitle()
}
runOnUiThread {
val locationAdapter = ArrayAdapter(this, R.layout.item_dropdown, locations)
binding.eventLocation.setAdapter(locationAdapter)
val titleAdapter = ArrayAdapter(this, R.layout.item_dropdown, eventTitleMap.keys.toList())
binding.eventTitle.setAdapter(titleAdapter)
}
val event = eventsDB.getEventWithId(eventId)
if (eventId != 0L && event == null) {
hideKeyboard()
finish()
return@ensureBackgroundThread
}
mStoredCalendars =
calendarsDB.getCalendars().toMutableList() as ArrayList<CalendarEntity>
val localCalendar =
mStoredCalendars.firstOrNull { it.id == config.lastUsedLocalCalendarId }
runOnUiThread {
if (!isDestroyed && !isFinishing) {
gotEvent(savedInstanceState, localCalendar, event)
}
}
}
}
override fun onResume() {
super.onResume()
setupTopAppBar()
}
private fun setupTopAppBar() {
setupTopAppBar(binding.eventAppbar, NavigationIcon.Arrow)
binding.eventToolbar.setNavigationOnClickListener {
maybeShowUnsavedChangesDialog {
hideKeyboard()
finish()
}
}
}
override fun onBackPressedCompat(): Boolean {
maybeShowUnsavedChangesDialog {
performDefaultBack()
}
return true
}
private fun maybeShowUnsavedChangesDialog(discard: () -> Unit) {
val now = System.currentTimeMillis()
if (now - mLastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL && isEventChanged()) {
mLastSavePromptTS = now
ConfirmationAdvancedDialog(
activity = this,
message = "",
messageId = org.fossify.commons.R.string.save_before_closing,
positive = org.fossify.commons.R.string.save,
negative = org.fossify.commons.R.string.discard
) {
if (it) {
saveCurrentEvent()
} else {
discard()
}
}
} else {
discard()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (!::mEvent.isInitialized) {
return
}
outState.apply {
putSerializable(EVENT, mEvent.copy(attendees = emptyList()))
putLong(START_TS, mEventStartDateTime.seconds())
putLong(END_TS, mEventEndDateTime.seconds())
putString(TIME_ZONE, mEvent.timeZone)
putInt(REMINDER_1_MINUTES, mReminder1Minutes)
putInt(REMINDER_2_MINUTES, mReminder2Minutes)
putInt(REMINDER_3_MINUTES, mReminder3Minutes)
putInt(REMINDER_1_TYPE, mReminder1Type)
putInt(REMINDER_2_TYPE, mReminder2Type)
putInt(REMINDER_3_TYPE, mReminder3Type)
putInt(REPEAT_INTERVAL, mRepeatInterval)
putInt(REPEAT_RULE, mRepeatRule)
putLong(REPEAT_LIMIT, mRepeatLimit)
putString(ATTENDEES, Gson().toJson(getAllAttendees(false)))
putString(ORIGINAL_ATTENDEES, Gson().toJson(mOriginalAttendees))
putInt(CLASS, mAccessLevel)
putInt(AVAILABILITY, mAvailability)
putInt(STATUS, mStatus)
putInt(EVENT_COLOR, mEventColor)
putLong(CALENDAR_ID, mCalendarId)
putInt(EVENT_CALENDAR_ID, mEventCalendarId)
putBoolean(IS_NEW_EVENT, mIsNewEvent)
putLong(ORIGINAL_START_TS, mOriginalStartTS)
putLong(ORIGINAL_END_TS, mOriginalEndTS)
}
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
if (!savedInstanceState.containsKey(START_TS)) {
hideKeyboard()
finish()
return
}
savedInstanceState.apply {
mEvent = getSerializable(EVENT) as Event
mEventStartDateTime = Formatter.getDateTimeFromTS(getLong(START_TS))
mEventEndDateTime = Formatter.getDateTimeFromTS(getLong(END_TS))
mEvent.timeZone = getString(TIME_ZONE) ?: TimeZone.getDefault().id
mReminder1Minutes = getInt(REMINDER_1_MINUTES)
mReminder2Minutes = getInt(REMINDER_2_MINUTES)
mReminder3Minutes = getInt(REMINDER_3_MINUTES)
mReminder1Type = getInt(REMINDER_1_TYPE)
mReminder2Type = getInt(REMINDER_2_TYPE)
mReminder3Type = getInt(REMINDER_3_TYPE)
mAccessLevel = getInt(CLASS)
mAvailability = getInt(AVAILABILITY)
mStatus = getInt(STATUS)
mEventColor = getInt(EVENT_COLOR)
mRepeatInterval = getInt(REPEAT_INTERVAL)
mRepeatRule = getInt(REPEAT_RULE)
mRepeatLimit = getLong(REPEAT_LIMIT)
val token = object : TypeToken<List<Attendee>>() {}.type
mAttendees =
Gson().fromJson<ArrayList<Attendee>>(getString(ATTENDEES), token) ?: ArrayList()
mOriginalAttendees =
Gson().fromJson<ArrayList<Attendee>>(getString(ORIGINAL_ATTENDEES), token)
?: ArrayList()
mEvent.attendees = mAttendees
mCalendarId = getLong(CALENDAR_ID)
mEventCalendarId = getInt(EVENT_CALENDAR_ID)
mIsNewEvent = getBoolean(IS_NEW_EVENT)
mOriginalStartTS = getLong(ORIGINAL_START_TS)
mOriginalEndTS = getLong(ORIGINAL_END_TS)
}
checkRepeatTexts(mRepeatInterval)
checkRepeatRule()
updateTexts()
updateCalendar()
checkAttendees()
updateActionBarTitle()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (
requestCode == SELECT_TIME_ZONE_INTENT
&& resultCode == RESULT_OK && resultData?.hasExtra(TIME_ZONE) == true
) {
val timeZone = resultData.getSerializableExtra(TIME_ZONE) as MyTimeZone
mEvent.timeZone = timeZone.zoneName
updateTimeZoneText()
}
super.onActivityResult(requestCode, resultCode, resultData)
}
private fun gotEvent(
savedInstanceState: Bundle?,
localCalendar: CalendarEntity?,
event: Event?,
) = binding.apply {
if (localCalendar == null || localCalendar.caldavCalendarId != 0) {
config.lastUsedLocalCalendarId = LOCAL_CALENDAR_ID
}
mCalendarId = if (config.defaultCalendarId == -1L) {
val lastCaldavId = config.lastUsedCaldavCalendarId
val canUseLastCaldav = config.caldavSync
&& lastCaldavId != STORED_LOCALLY_ONLY
&& config.getSyncedCalendarIdsAsList().contains(lastCaldavId)
if (canUseLastCaldav) {
mStoredCalendars.firstOrNull { it.caldavCalendarId == lastCaldavId }?.id
?: config.lastUsedLocalCalendarId
} else {
config.lastUsedLocalCalendarId
}
} else {
mStoredCalendars.firstOrNull { it.id == config.defaultCalendarId }?.id
?: config.lastUsedLocalCalendarId
}
if (event != null) {
mEvent = event
mEventOccurrenceTS = intent.getLongExtra(EVENT_OCCURRENCE_TS, 0L)
if (savedInstanceState == null) {
setupEditEvent()
}
if (intent.getBooleanExtra(IS_DUPLICATE_INTENT, false)) {
mEvent.id = null
eventToolbar.title = getString(R.string.new_event)
} else {
cancelNotification(mEvent.id!!)
}
} else {
mEvent = Event(null)
config.apply {
mReminder1Minutes =
if (usePreviousEventReminders && lastEventReminderMinutes1 >= -1) {
lastEventReminderMinutes1
} else {
defaultReminder1
}
mReminder2Minutes =
if (usePreviousEventReminders && lastEventReminderMinutes2 >= -1) {
lastEventReminderMinutes2
} else {
defaultReminder2
}
mReminder3Minutes =
if (usePreviousEventReminders && lastEventReminderMinutes3 >= -1) {
lastEventReminderMinutes3
} else {
defaultReminder3
}
}
if (savedInstanceState == null) {
setupNewEvent()
}
}
if (savedInstanceState == null) {
updateCalendar()
updateTexts()
}
eventShowOnMap.setOnClickListener { showOnMap() }
eventStartDate.setOnClickListener { setupStartDate() }
eventStartTime.setOnClickListener { setupStartTime() }
eventEndDate.setOnClickListener { setupEndDate() }
eventEndTime.setOnClickListener { setupEndTime() }
eventTimeZone.setOnClickListener { setupTimeZone() }
eventAllDay.setOnCheckedChangeListener { _, isChecked -> toggleAllDay(isChecked) }
eventRepetition.setOnClickListener { showRepeatIntervalDialog() }
eventRepetitionRuleHolder.setOnClickListener { showRepetitionRuleDialog() }
eventRepetitionLimitHolder.setOnClickListener { showRepetitionTypePicker() }
eventReminder1.setOnClickListener {
handleNotificationAvailability {
if (config.wasAlarmWarningShown) {
showReminder1Dialog()
} else {
ReminderWarningDialog(this@EventActivity) {
config.wasAlarmWarningShown = true
showReminder1Dialog()
}
}
}
}
eventReminder2.setOnClickListener { showReminder2Dialog() }
eventReminder3.setOnClickListener { showReminder3Dialog() }
eventReminder1Type.setOnClickListener {
showReminderTypePicker(mReminder1Type) {
mReminder1Type = it
updateReminderTypeImage(
view = eventReminder1Type,
reminder = Reminder(mReminder1Minutes, mReminder1Type)
)
}
}
eventReminder2Type.setOnClickListener {
showReminderTypePicker(mReminder2Type) {
mReminder2Type = it
updateReminderTypeImage(
view = eventReminder2Type,
reminder = Reminder(mReminder2Minutes, mReminder2Type)
)
}
}
eventReminder3Type.setOnClickListener {
showReminderTypePicker(mReminder3Type) {
mReminder3Type = it
updateReminderTypeImage(
view = eventReminder3Type,
reminder = Reminder(mReminder3Minutes, mReminder3Type)
)
}
}
eventAccessLevel.setOnClickListener {
showAccessLevelPicker(mAccessLevel) {
mAccessLevel = it
updateAccessLevelText()
}
}
eventAvailability.setOnClickListener {
showAvailabilityPicker(mAvailability) {
mAvailability = it
updateAvailabilityText()
}
}
eventStatus.setOnClickListener {
showStatusPicker(mStatus) {
mStatus = it
updateStatusText()
}
}
eventCalendarHolder.setOnClickListener { showCalendarDialog() }
eventAllDay.apply {
isChecked = mEvent.getIsAllDay()
jumpDrawablesToCurrentState()
}
eventAllDayHolder.setOnClickListener {
eventAllDay.toggle()
}
eventColorHolder.setOnClickListener {
showEventColorDialog()
}
updateTextColors(eventNestedScrollview)
updateIconColors()
refreshMenuItems()
showOrHideTimeZone()
}
private fun refreshMenuItems() {
if (::mEvent.isInitialized) {
binding.eventToolbar.menu.apply {
findItem(R.id.delete).isVisible = mEvent.id != null
findItem(R.id.share).isVisible = mEvent.id != null
findItem(R.id.duplicate).isVisible = mEvent.id != null
}
}
}
private fun setupOptionsMenu() {
binding.eventToolbar.setOnMenuItemClickListener { menuItem ->
if (!::mEvent.isInitialized) {
return@setOnMenuItemClickListener true
}
when (menuItem.itemId) {
R.id.save -> saveCurrentEvent()
R.id.delete -> deleteEvent()
R.id.duplicate -> duplicateEvent()
R.id.share -> shareEvent()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
private fun getStartEndTimes(): Pair<Long, Long> {
if (mIsAllDayEvent) {
val newStartTS = mEventStartDateTime.withTimeAtStartOfDay().seconds()
val newEndTS = mEventEndDateTime.withTimeAtStartOfDay().withHourOfDay(12).seconds()
return Pair(newStartTS, newEndTS)
} else {
val offset = if (
!config.allowChangingTimeZones
|| mEvent.getTimeZoneString().equals(mOriginalTimeZone, true)
) {
0
} else {
val original = mOriginalTimeZone.ifEmpty { DateTimeZone.getDefault().id }
val millis = System.currentTimeMillis()
val newOffset = DateTimeZone.forID(mEvent.getTimeZoneString()).getOffset(millis)
val oldOffset = DateTimeZone.forID(original).getOffset(millis)
(newOffset - oldOffset) / 1000L
}
val newStartTS = mEventStartDateTime.seconds() - offset
val newEndTS = mEventEndDateTime.seconds() - offset
return Pair(newStartTS, newEndTS)
}
}
private fun getReminders(): ArrayList<Reminder> {
return arrayListOf(
Reminder(mReminder1Minutes, mReminder1Type),
Reminder(mReminder2Minutes, mReminder2Type),
Reminder(mReminder3Minutes, mReminder3Type)
).filter { it.minutes != REMINDER_OFF }
.sortedBy { it.minutes }
.toMutableList() as ArrayList<Reminder>
}
private fun isEventChanged(): Boolean {
if (!::mEvent.isInitialized) {
return false
}
var newStartTS: Long
var newEndTS: Long
getStartEndTimes().apply {
newStartTS = first
newEndTS = second
}
val hasTimeChanged = if (mOriginalStartTS == 0L) {
mEvent.startTS != newStartTS || mEvent.endTS != newEndTS
} else {
mOriginalStartTS != newStartTS || mOriginalEndTS != newEndTS
}
val reminders = getReminders()
return binding.eventTitle.text.toString() != mEvent.title ||
binding.eventLocation.text.toString() != mEvent.location ||
binding.eventDescription.text.toString() != mEvent.description ||
binding.eventTimeZone.text != mEvent.getTimeZoneString() ||
reminders != mEvent.getReminders() ||
mRepeatInterval != mEvent.repeatInterval ||
mRepeatRule != mEvent.repeatRule ||
mRepeatLimit != mEvent.repeatLimit ||
attendeesChanged() ||
mAvailability != mEvent.availability ||
mAccessLevel != mEvent.accessLevel ||
mStatus != mEvent.status ||
mCalendarId != mEvent.calendarId ||
mWasCalendarChanged ||
mIsAllDayEvent != mEvent.getIsAllDay() ||
mEventColor != mEvent.color ||
hasTimeChanged
}
private fun attendeesChanged(): Boolean {
val currentAttendees = getAllAttendees(false).sortedBy { it.email }
val originalAttendees = mOriginalAttendees.sortedBy { it.email }
if (currentAttendees.size != originalAttendees.size) {
return true
}
return currentAttendees.zip(originalAttendees).any { (first, second) ->
first.email != second.email ||
first.status != second.status ||
first.relationship != second.relationship
}
}
private fun updateTexts() {
updateRepetitionText()
checkReminderTexts()
updateStartTexts()
updateEndTexts()
updateTimeZoneText()
updateCalDAVVisibility()
updateAvailabilityText()
updateStatusText()
updateAccessLevelText()
}
private fun setupEditEvent() {
mIsNewEvent = false
val realStart = if (mEventOccurrenceTS == 0L) mEvent.startTS else mEventOccurrenceTS
val duration = mEvent.endTS - mEvent.startTS
mOriginalStartTS = realStart
mOriginalEndTS = realStart + duration
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
binding.eventToolbar.title = getString(R.string.edit_event)
mOriginalTimeZone = mEvent.timeZone
if (config.allowChangingTimeZones) {
try {
mEventStartDateTime = Formatter.getDateTimeFromTS(realStart)
.withZone(DateTimeZone.forID(mOriginalTimeZone))
mEventEndDateTime = Formatter.getDateTimeFromTS(realStart + duration)
.withZone(DateTimeZone.forID(mOriginalTimeZone))
} catch (e: Exception) {
showErrorToast(e)
mEventStartDateTime = Formatter.getDateTimeFromTS(realStart)
mEventEndDateTime = Formatter.getDateTimeFromTS(realStart + duration)
}
} else {
mEventStartDateTime = Formatter.getDateTimeFromTS(realStart)
mEventEndDateTime = Formatter.getDateTimeFromTS(realStart + duration)
}
binding.eventTitle.setText(mEvent.title)
binding.eventLocation.setText(mEvent.location)
binding.eventDescription.setText(mEvent.description)
mReminder1Minutes = mEvent.reminder1Minutes
mReminder2Minutes = mEvent.reminder2Minutes
mReminder3Minutes = mEvent.reminder3Minutes
mReminder1Type = mEvent.reminder1Type
mReminder2Type = mEvent.reminder2Type
mReminder3Type = mEvent.reminder3Type
mRepeatInterval = mEvent.repeatInterval
mRepeatLimit = mEvent.repeatLimit
mRepeatRule = mEvent.repeatRule
mCalendarId = mEvent.calendarId
mEventCalendarId = mEvent.getCalDAVCalendarId()
mAvailability = mEvent.availability
mAccessLevel = mEvent.accessLevel
mStatus = mEvent.status
mEventColor = mEvent.color
mAttendees = mEvent.attendees.toMutableList() as ArrayList<Attendee>
mOriginalAttendees = mAttendees.map { it.copy() }.toMutableList() as ArrayList<Attendee>
checkRepeatTexts(mRepeatInterval)
checkAttendees()
}
private fun setupNewEvent() {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
binding.eventTitle.requestFocus()
binding.eventToolbar.title = getString(R.string.new_event)
val selectedCalendar = mStoredCalendars.firstOrNull { it.id == mCalendarId }
val selectedCaldavId = selectedCalendar?.caldavCalendarId ?: 0
val isSelectedCaldavOk =
selectedCaldavId != 0 && config.caldavSync && config.getSyncedCalendarIdsAsList()
.contains(selectedCaldavId)
if (isSelectedCaldavOk) {
mEventCalendarId = selectedCaldavId
} else {
mEventCalendarId = STORED_LOCALLY_ONLY
if (selectedCalendar == null || selectedCalendar.caldavCalendarId != 0) {
mCalendarId = config.lastUsedLocalCalendarId
}
}
if (intent.action == Intent.ACTION_EDIT || intent.action == Intent.ACTION_INSERT) {
val startTS = intent.getLongExtra("beginTime", System.currentTimeMillis()) / 1000L
mEventStartDateTime = Formatter.getDateTimeFromTS(startTS)
val endTS = intent.getLongExtra("endTime", System.currentTimeMillis()) / 1000L
mEventEndDateTime = Formatter.getDateTimeFromTS(endTS)
if (intent.getBooleanExtra("allDay", false)) {
mEvent.flags = mEvent.flags or FLAG_ALL_DAY
binding.eventAllDay.isChecked = true
toggleAllDay(true)
}
binding.eventTitle.setText(intent.getStringExtra("title"))
binding.eventLocation.setText(intent.getStringExtra("eventLocation"))
binding.eventDescription.setText(intent.getStringExtra("description"))
if (binding.eventDescription.value.isNotEmpty()) {
binding.eventDescription.movementMethod = LinkMovementMethod.getInstance()
}
} else {
val startTS = intent.getLongExtra(NEW_EVENT_START_TS, 0L)
val dateTime = Formatter.getDateTimeFromTS(startTS)
mEventStartDateTime = dateTime
val addMinutes = if (intent.getBooleanExtra(NEW_EVENT_SET_HOUR_DURATION, false)) {
// if an event is created at 23:00 on the weekly view, make it end
// on 23:59 by default to avoid spanning across multiple days
if (mEventStartDateTime.hourOfDay == 23) 59 else 60
} else {
config.defaultDuration
}
mEventEndDateTime = mEventStartDateTime.plusMinutes(addMinutes)
}
addDefValuesToNewEvent()
checkAttendees()
}
private fun addDefValuesToNewEvent() {
var newStartTS: Long
var newEndTS: Long
getStartEndTimes().apply {
newStartTS = first
newEndTS = second
}
mEvent.apply {
startTS = newStartTS
endTS = newEndTS
reminder1Minutes = mReminder1Minutes
reminder1Type = mReminder1Type
reminder2Minutes = mReminder2Minutes
reminder2Type = mReminder2Type
reminder3Minutes = mReminder3Minutes
reminder3Type = mReminder3Type
status = mStatus
calendarId = mCalendarId
}
}
private fun checkAttendees() {
ensureBackgroundThread {
fillAvailableContacts()
updateAttendees()
}
}
private fun showReminder1Dialog() {
showPickSecondsDialogHelper(mReminder1Minutes, showDuringDayOption = mIsAllDayEvent) {
mReminder1Minutes = if (it == -1 || it == 0) it else it / 60
checkReminderTexts()
}
}
private fun showReminder2Dialog() {
showPickSecondsDialogHelper(mReminder2Minutes, showDuringDayOption = mIsAllDayEvent) {
mReminder2Minutes = if (it == -1 || it == 0) it else it / 60
checkReminderTexts()
}
}
private fun showReminder3Dialog() {
showPickSecondsDialogHelper(mReminder3Minutes, showDuringDayOption = mIsAllDayEvent) {
mReminder3Minutes = if (it == -1 || it == 0) it else it / 60
checkReminderTexts()
}
}
private fun showRepeatIntervalDialog() {
showEventRepeatIntervalDialog(mRepeatInterval) {
setRepeatInterval(it)
}
}
private fun setRepeatInterval(interval: Int) {
mRepeatInterval = interval
updateRepetitionText()
checkRepeatTexts(interval)
when {
mRepeatInterval.isXWeeklyRepetition() -> setRepeatRule(1 shl (mEventStartDateTime.dayOfWeek - 1))
mRepeatInterval.isXMonthlyRepetition() -> setRepeatRule(REPEAT_SAME_DAY)
mRepeatInterval.isXYearlyRepetition() -> setRepeatRule(REPEAT_SAME_DAY)
}
}
private fun checkRepeatTexts(limit: Int) {
binding.eventRepetitionLimitHolder.beGoneIf(limit == 0)
checkRepetitionLimitText()
binding.eventRepetitionRuleHolder.beVisibleIf(
beVisible = mRepeatInterval.isXWeeklyRepetition()
|| mRepeatInterval.isXMonthlyRepetition()
|| mRepeatInterval.isXYearlyRepetition()
)
checkRepetitionRuleText()
}
private fun showRepetitionTypePicker() {
hideKeyboard()
RepeatLimitTypePickerDialog(this, mRepeatLimit, mEventStartDateTime.seconds()) {
setRepeatLimit(it)
}
}
private fun setRepeatLimit(limit: Long) {
mRepeatLimit = limit
checkRepetitionLimitText()
}
private fun checkRepetitionLimitText() {
binding.eventRepetitionLimit.text = when {
mRepeatLimit == 0L -> {
binding.eventRepetitionLimitLabel.text = getString(R.string.repeat)
resources.getString(R.string.forever)
}
mRepeatLimit > 0 -> {
binding.eventRepetitionLimitLabel.text = getString(R.string.repeat_till)
val repeatLimitDateTime = Formatter.getDateTimeFromTS(mRepeatLimit)
Formatter.getFullDate(this, repeatLimitDateTime)
}
else -> {
binding.eventRepetitionLimitLabel.text = getString(R.string.repeat)
"${-mRepeatLimit} ${getString(R.string.times)}"
}
}
}
private fun showRepetitionRuleDialog() {
hideKeyboard()
when {
mRepeatInterval.isXWeeklyRepetition() -> RepeatRuleWeeklyDialog(this, mRepeatRule) {
setRepeatRule(it)
}
mRepeatInterval.isXMonthlyRepetition() -> {
val items = getAvailableMonthlyRepetitionRules()
RadioGroupDialog(this, items, mRepeatRule) {
setRepeatRule(it as Int)
}
}
mRepeatInterval.isXYearlyRepetition() -> {
val items = getAvailableYearlyRepetitionRules()
RadioGroupDialog(this, items, mRepeatRule) {
setRepeatRule(it as Int)
}
}
}
}
private fun getAvailableMonthlyRepetitionRules(): ArrayList<RadioItem> {
val items = arrayListOf(
RadioItem(
id = REPEAT_SAME_DAY,
title = getString(R.string.repeat_on_the_same_day_monthly)
)
)
items.add(
RadioItem(
id = REPEAT_ORDER_WEEKDAY,
title = getRepeatXthDayString(true, REPEAT_ORDER_WEEKDAY)
)