# -rw-r--r-- 23.1 KiB View raw
                                                                                
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
diff --git a/Makefile b/Makefile
index 6804dff..3f07143 100644
--- a/Makefile
+++ b/Makefile
@@ -5,7 +5,6 @@ PREFIX:=/usr
 PROGRAMS = \
 	programs/sxmo_setpineled \
 	programs/sxmo_setpinebacklight \
-	programs/sxmo_screenlock \
 	programs/sxmo_megiaudioroute \
 	programs/sxmo_vibratepine
 
@@ -22,9 +21,6 @@ programs/sxmo_setpineled: programs/sxmo_setpineled.c
 programs/sxmo_setpinebacklight: programs/sxmo_setpinebacklight.c
 	gcc -o programs/sxmo_setpinebacklight programs/sxmo_setpinebacklight.c
 
-programs/sxmo_screenlock: programs/sxmo_screenlock.c
-	gcc -o programs/sxmo_screenlock programs/sxmo_screenlock.c -lX11
-
 programs/sxmo_megiaudioroute: programs/sxmo_megiaudioroute.c
 	gcc -o programs/sxmo_megiaudioroute programs/sxmo_megiaudioroute.c
 
@@ -32,7 +28,7 @@ programs/sxmo_vibratepine: programs/sxmo_vibratepine.c
 	gcc -o programs/sxmo_vibratepine programs/sxmo_vibratepine.c
 
 clean:
-	rm -f programs/sxmo_setpineled programs/sxmo_screenlock programs/sxmo_setpinebacklight programs/sxmo_megiaudioroute programs/sxmo_vibratepine
+	rm -f programs/sxmo_setpineled programs/sxmo_setpinebacklight programs/sxmo_megiaudioroute programs/sxmo_vibratepine
 
 install: $(PROGRAMS)
 	cd configs && find . -type f -exec install -D -m 0644 "{}" "$(DESTDIR)$(PREFIX)/share/sxmo/{}" \; && cd ..
@@ -63,8 +59,6 @@ install: $(PROGRAMS)
 
 	install -D -m 0755 programs/sxmo_setpinebacklight $(DESTDIR)$(PREFIX)/bin/
 
-	install -D -m 0755 programs/sxmo_screenlock $(DESTDIR)$(PREFIX)/bin/
-
 	install -D programs/sxmo_megiaudioroute $(DESTDIR)$(PREFIX)/bin/
 	install -D programs/sxmo_vibratepine $(DESTDIR)$(PREFIX)/bin/
 
diff --git a/programs/sxmo_screenlock.c b/programs/sxmo_screenlock.c
deleted file mode 100644
index 0e78193..0000000
--- a/programs/sxmo_screenlock.c
+++ /dev/null
@@ -1,553 +0,0 @@
-#include <dirent.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <signal.h>
-#include <time.h>
-#include <X11/keysym.h>
-#include <X11/XF86keysym.h>
-#include <X11/XKBlib.h>
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-#include <sys/ioctl.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <linux/rtc.h>
-
-// Types
-enum State {
-	StateNoInput,		 // Screen on / input lock
-	StateNoInputNoScreen, // Screen off / input lock
-	StateSuspend,		 // Deep sleep
-	StateSuspendPending,  // Suspend 'woken up', must leave state in <5s, or kicks to StateSuspend
-	StateDead			 // Exit the appliation
-};
-enum Color {
-	Red,
-	Blue,
-	Purple,
-	Off
-};
-
-// Fn declarations
-int checkrtcwake();
-void configuresuspendsettingsandwakeupsources();
-time_t convert_rtc_time(struct rtc_time * rtc);
-void die(const char *err, ...);
-int getoldbrightness();
-void init_rtc();
-void lockscreen(Display *dpy, int screen, int blank);
-void unblankscreen();
-void blankscreen();
-void readinputloop(Display *dpy, int screen);
-int presuspend();
-void postwake();
-void setpineled(enum Color c);
-int setup_rtc_wakeup();
-void sigterm();
-void syncstate();
-void usage();
-void writefile(char *filepath, char *str);
-
-// Variables
-Display *dpy;
-Window root;
-enum State state = StateNoInput;
-int suspendtimeouts = 35;
-int suspendpendingsceenon = 0;
-int suspendpendingtimeouts = 0;
-KeySym lastkeysym = XK_Cancel;
-int lastkeyn = 0;
-char oldbrightness[10] = "200";
-char * brightnessfile = "/sys/devices/platform/backlight/backlight/backlight/brightness";
-char * powerstatefile = "/sys/power/state";
-int rtc_fd = 0; //file descriptor
-time_t wakeinterval = 0; //wake every x seconds
-time_t waketime = 0; //next wakeup time according to the RTC clock
-int slept = 0; //indicates whether the process has slept (crust) or not
-int blanked = 0; //indicated whether the display blanked or not
-
-#define RTC_DEVICE	  "/dev/rtc0"
-
-time_t
-convert_rtc_time(struct rtc_time * rtc) {
-	struct tm		 tm;
-	memset(&tm, 0, sizeof tm);
-	tm.tm_sec = rtc->tm_sec;
-	tm.tm_min = rtc->tm_min;
-	tm.tm_hour = rtc->tm_hour;
-	tm.tm_mday = rtc->tm_mday;
-	tm.tm_mon = rtc->tm_mon;
-	tm.tm_year = rtc->tm_year;
-	tm.tm_isdst = -1;  /* assume the system knows better than the RTC */
-	return mktime(&tm);
-}
-
-int setup_rtc_wakeup() {
-	//(code adapted from util-linux's rtcwake)
-	struct tm		 *tm;
-	struct rtc_wkalrm	wake;
-	struct rtc_time now_rtc;
-
-	if (ioctl(rtc_fd, RTC_RD_TIME, &now_rtc) < 0) {
-		fprintf(stderr, "Error reading rtc time
");
-	}
-	const time_t now = convert_rtc_time(&now_rtc);
-	waketime = now + wakeinterval;
-
-	tm = localtime(&waketime);
-
-	wake.time.tm_sec = tm->tm_sec;
-	wake.time.tm_min = tm->tm_min;
-	wake.time.tm_hour = tm->tm_hour;
-	wake.time.tm_mday = tm->tm_mday;
-	wake.time.tm_mon = tm->tm_mon;
-	wake.time.tm_year = tm->tm_year;
-	/* wday, yday, and isdst fields are unused by Linux */
-	wake.time.tm_wday = -1;
-	wake.time.tm_yday = -1;
-	wake.time.tm_isdst = -1;
-
-	fprintf(stderr, "Setting RTC wakeup to %ld: (UTC) %s", waketime, asctime(tm));
-
-	if (ioctl(rtc_fd, RTC_ALM_SET, &wake.time) < 0) {
-		fprintf(stderr, "error setting rtc alarm
");
-		return -1;
-	}
-	if (ioctl(rtc_fd, RTC_AIE_ON, 0) < 0) {
-		fprintf(stderr, "error enabling rtc alarm
");
-		return -1;
-	}
-	return 0;
-}
-
-void
-configuresuspendsettingsandwakeupsources()
-{
-	// Disable all wakeup sources
-	struct dirent *wakeupsource;
-	char wakeuppath[100];
-	DIR *wakeupsources = opendir("/sys/class/wakeup");
-	if (wakeupsources == NULL)
-		die("Couldn't open directory /sys/class/wakeup
");
-	while ((wakeupsource = readdir(wakeupsources)) != NULL) {
-		sprintf(
-			wakeuppath,
-			"/sys/class/wakeup/%.50s/device/power/wakeup",
-			wakeupsource->d_name
-		);
-		fprintf(stderr, "Disabling wakeup source: %s", wakeupsource->d_name);
-		writefile(wakeuppath, "disabled");
-		fprintf(stderr, ".. ok
");
-	}
-	closedir(wakeupsources);
-
-	// Enable powerbutton wakeup source
-	fprintf(stderr, "Enable powerbutton wakeup source
");
-	writefile(
-		"/sys/devices/platform/soc/1f03400.rsb/sunxi-rsb-3a3/axp221-pek/power/wakeup",
-		"enabled"
-	);
-
-	// Enable IRQ wakeup source (incoming call) 5.10
-	fprintf(stderr, "Enable 5.10 IRQ wakeup source
");
-	writefile(
-		"/sys/devices/platform/gpio-keys/power/wakeup",
-		"enabled"
-	 );
-
-	 // Enable IRQ wakeup source (incoming call) 5.9 (no longer exists in 5.10)
-	fprintf(stderr, "Enable 5.9 IRQ wakeup source
");
-	writefile(
-		"/sys/devices/platform/soc/1c28c00.serial/serial1/serial1-0/power/wakeup",
-		"enabled"
-	 );
-
-	// Enable rtc wakeup source
-	fprintf(stderr, "Enable rtc wakeup source
");
-	writefile(
-		"/sys/devices/platform/soc/1f00000.rtc/power/wakeup",
-		"enabled"
-	);
-
-	//set RTC wake
-	if (wakeinterval > 0) setup_rtc_wakeup();
-
-	// E.g. make sure we're using CRUST
-	fprintf(stderr, "Flip mem_sleep setting to use crust
");
-	writefile("/sys/power/mem_sleep", "deep");
-
-}
-
-void
-die(const char *err, ...)
-{
-	fprintf(stderr, "Screenlock error: %s
", err);
-	state = StateDead;
-	syncstate();
-	exit(1);
-}
-
-void
-sigterm()
-{
-	state = StateDead;
-	syncstate();
-	if (wakeinterval) {
-		ioctl(rtc_fd, RTC_AIE_OFF, 0);
-		close(rtc_fd);
-	}
-	fprintf(stderr, "Screenlock terminating on signal
");
-	exit(0);
-}
-
-int
-getoldbrightness() {
-	char * buffer = 0;
-	long length;
-	FILE * f = fopen(brightnessfile, "r");
-	if (f) {
-		fseek(f, 0, SEEK_END);
-		length = ftell(f);
-		fseek(f, 0, SEEK_SET);
-		buffer = malloc(length);
-		if (buffer) {
-			fread(buffer, 1, length, f);
-		}
-		fclose(f);
-	}
-	if (buffer) {
-		sprintf(oldbrightness, "%d", atoi(buffer));
-	}
-}
-
-
-void
-lockscreen(Display *dpy, int screen, int blank)
-{
-	// Loosely derived from suckless' slock's lockscreen binding logic but
-	// alot more coarse, intentionally so can be triggered while grab_key
-	// for dwm multikey path already holding..
-	int i, ptgrab, kbgrab;
-	root = RootWindow(dpy, screen);
-	if (blank == 1) {
-		blankscreen();
-	}
-	for (i = 0, ptgrab = kbgrab = -1; i < 9999999; i++) {
-		if (ptgrab != GrabSuccess) {
-			ptgrab = XGrabPointer(dpy, root, False,
-				ButtonPressMask | ButtonReleaseMask |
-				PointerMotionMask, GrabModeAsync,
-				GrabModeAsync, None, None, CurrentTime);
-		}
-		if (kbgrab != GrabSuccess) {
-			kbgrab = XGrabKeyboard(dpy, root, True,
-				GrabModeAsync, GrabModeAsync, CurrentTime);
-		}
-		if (ptgrab == GrabSuccess && kbgrab == GrabSuccess) {
-			XSelectInput(dpy, root, SubstructureNotifyMask);
-			return;
-		}
-		usleep(100000);
-	}
-}
-
-void
-blankscreen()
-{
-	if (!blanked) {
-		system("xset dpms force off");
-		blanked = 1;
-	}
-}
-
-void
-unblankscreen()
-{
-	if (blanked) {
-		system("xset dpms force on");
-		blanked = 0;
-	}
-}
-
-void
-readinputloop(Display *dpy, int screen) {
-	KeySym keysym;
-	XEvent ev;
-	char buf[32];
-	fd_set fdset;
-	int xfd;
-	int selectresult;
-	struct timeval xeventtimeout = {1, 0};
-	xfd = ConnectionNumber(dpy);
-
-	for (;;) {
-		FD_ZERO(&fdset);
-		FD_SET(xfd, &fdset);
-		if (state == StateSuspendPending)
-			selectresult = select(FD_SETSIZE, &fdset, NULL, NULL, &xeventtimeout);
-		else
-			selectresult = select(FD_SETSIZE, &fdset, NULL, NULL, NULL);
-
-		if (FD_ISSET(xfd, &fdset) && XPending(dpy)) {
-			XNextEvent(dpy, &ev);
-			if (ev.type == KeyRelease) {
-				XLookupString(&ev.xkey, buf, sizeof(buf), &keysym, 0);
-				if (lastkeysym == keysym) {
-					lastkeyn++;
-				} else {
-					lastkeysym = keysym;
-					lastkeyn = 1;
-				}
-
-				if (lastkeyn < 3)
-					continue;
-
-				lastkeyn = 0;
-				lastkeysym = XK_Cancel;
-				if (slept) postwake();
-				switch (keysym) {
-					case XF86XK_AudioRaiseVolume:
-						suspendpendingsceenon = state == StateNoInput;
-						suspendpendingtimeouts = 0;
-						state = StateSuspend;
-						break;
-					case XF86XK_AudioLowerVolume:
-						if (state == StateNoInput) state = StateNoInputNoScreen;
-						else if (state == StateNoInputNoScreen) state = StateNoInput;
-						else if (state == StateSuspendPending && suspendpendingsceenon) state = StateNoInputNoScreen;
-						else state = StateNoInput;
-						break;
-					case XF86XK_PowerOff:
-						waketime = 0;
-						state = StateDead;
-						break;
-				}
-				syncstate();
-			}
-		} else if (state == StateSuspendPending) {
-			suspendpendingtimeouts++;
-			// # E.g. after suspendtimeouts seconds kick back into suspend
-			if (suspendpendingtimeouts > suspendtimeouts) state = StateSuspend;
-			syncstate();
-		}
-
-
-		if (state == StateDead) break;
-	}
-}
-
-void
-setpineled(enum Color c)
-{
-	if (c == Red) {
-		writefile("/sys/class/leds/red:indicator/brightness", "1");
-		writefile("/sys/class/leds/blue:indicator/brightness", "0");
-	} else if (c == Blue) {
-		writefile("/sys/class/leds/red:indicator/brightness", "0");
-		writefile("/sys/class/leds/blue:indicator/brightness", "1");
-	} else if (c == Purple) {
-		writefile("/sys/class/leds/red:indicator/brightness", "1");
-		writefile("/sys/class/leds/blue:indicator/brightness", "1");
-	} else if (c == Off) {
-		writefile("/sys/class/leds/red:indicator/brightness", "0");
-		writefile("/sys/class/leds/blue:indicator/brightness", "0");
-	}
-}
-
-int
-presuspend() {
-	//called prior to suspension, a non-zero return value cancels suspension
-	return system("sxmo_presuspend.sh");
-}
-
-void
-postwake() {
-	//called after fully waking up (not used for temporary rtc wakeups)
-	system("sxmo_postwake.sh");
-	slept = 0;
-}
-
-int
-checkrtcwake()
-{
-	struct rtc_time now;
-	if (ioctl(rtc_fd, RTC_RD_TIME, &now) < 0) {
-		fprintf(stderr, "Error reading rtc time
");
-		return -1;
-	}
-
-	const long int timediff = convert_rtc_time(&now) - waketime;
-	fprintf(stderr, "Checking rtc wake? timediff=%ld
", timediff);
-	if (timediff >= 0 && timediff <= 3) {
-		fprintf(stderr, "Calling RTC wake script
");
-		setpineled(Blue);
-		return system("sxmo_rtcwake.sh");
-	}
-	return 0;
-}
-
-void
-syncstate()
-{
-	int rtcresult;
-	if (state == StateSuspend) {
-		if (presuspend() != 0) {
-			state = StateDead;
-		} else {
-			fprintf(stderr, "Screenlock entering suspend state (pred mode)
");
-			writefile(brightnessfile, "0");
-			blankscreen();
-			slept = 1;
-			setpineled(Red);
-			configuresuspendsettingsandwakeupsources();
-			writefile(powerstatefile, "mem");
-			//---- program blocks here due to sleep ----- //
-			// Just woke up again
-			fprintf(stderr, "Screenlock woke up
");
-			fprintf(stderr, "Lower scan interval for quicker reconnection to wireless network
");
-			writefile("/sys/module/8723cs/parameters/rtw_scan_interval_thr", "1200"); //ms
-			//^-- this will be undone again by a networkmanager hook after connection has been established
-			//    or by a delayed script if no connection can be established after a while (to conserve battery)
-			fprintf(stderr, "Woke up
");
-			if (waketime > 0) {
-				rtcresult = checkrtcwake();
-			} else {
-				rtcresult = 0;
-			}
-			if (rtcresult == 0) {
-				state = StateSuspendPending;
-				suspendpendingtimeouts = 0;
-			} else {
-				postwake();
-				state = StateDead;
-			}
-		}
-		syncstate();
-	} else if (state == StateNoInput) {
-		fprintf(stderr, "Screenlock in no Input state (blue mode)
");
-		setpineled(Blue);
-		unblankscreen();
-		writefile(brightnessfile, oldbrightness);
-	} else if (state == StateNoInputNoScreen) {
-		fprintf(stderr, "Screenlock in no screen state (purple mode)
");
-		setpineled(Purple);
-		writefile(brightnessfile, "0");
-		blankscreen();
-	} else if (state == StateSuspendPending) {
-		fprintf(stderr, "Screenlock is pending suspension
");
-		if (suspendpendingsceenon) unblankscreen();
-		writefile(brightnessfile, suspendpendingsceenon ? oldbrightness : "0");
-		if (!suspendpendingsceenon) blankscreen();
-		setpineled(Off);
-		usleep(1000 * 100);
-		setpineled(suspendpendingsceenon ? Blue : Purple);
-	} else if (state == StateDead) {
-		unblankscreen();
-		writefile(brightnessfile, oldbrightness);
-		setpineled(Off);
-	}
-}
-
-
-
-
-void
-writefile(char *filepath, char *str)
-{
-	int f;
-	f = open(filepath, O_WRONLY);
-	if (f != -1) {
-		write(f, str, strlen(str));
-		close(f);
-	} else {
-		fprintf(stderr, "Couldn't open filepath <%s>
", filepath);
-	}
-}
-
-void usage() {
-	fprintf(stderr, "Usage: sxmo_screenlock [--screen-off] [--suspend] [--wake-interval n] [--setuid]
");
-}
-
-
-void init_rtc() {
-	rtc_fd = open(RTC_DEVICE, O_RDONLY);
-	if (rtc_fd < 0) {
-		fprintf(stderr, "Error opening rtc device: %d
", rtc_fd);
-		die("Unable to open rtc device");
-		exit(EXIT_FAILURE);
-	}
-}
-
-int
-main(int argc, char **argv) {
-	int screen;
-	int i;
-	enum State target = StateNoInput;
-
-	signal(SIGTERM, sigterm);
-
-	const char* suspendtimeouts_str = getenv("SXMO_SUSPENDTIMEOUTS");
-	if (suspendtimeouts_str != NULL) suspendtimeouts = atoi(suspendtimeouts_str);
-
-	const char* rtcwakeinterval = getenv("SXMO_RTCWAKEINTERVAL");
-	if (rtcwakeinterval != NULL) wakeinterval = atoi(rtcwakeinterval);
-
-	const char* screen_off = getenv("SXMO_LOCK_SCREEN_OFF");
-	if (screen_off != NULL && atoi(screen_off)) target = StateNoInputNoScreen;
-
-	const char* suspend = getenv("SXMO_LOCK_SUSPEND");
-	if (suspend != NULL && atoi(suspend)) target = StateSuspend;
-
-	//parse command line arguments
-	for (i = 1; i < argc; i++) {
-		if(!strcmp(argv[i], "-h")) {
-			usage();
-			return 0;
-		} else if(!strcmp(argv[i], "--screen-off")) {
-			target = StateNoInputNoScreen;
-		} else if(!strcmp(argv[i], "--suspend")) {
-			target = StateSuspend;
-		} else if(!strcmp(argv[i], "--wake-interval")) {
-			wakeinterval = (time_t) atoi(argv[++i]);
-		} else if(!strcmp(argv[i], "--setuid")) {
-			if (setuid(0))
-				die("setuid(0) failed");
-		} else {
-			fprintf(stderr, "Invalid argument: %s
", argv[i]);
-			return 2;
-		}
-	}
-
-	if (!(dpy = XOpenDisplay(NULL)))
-		die("Cannot open display");
-
-	getoldbrightness();
-
-	if (wakeinterval) init_rtc();
-
-	fprintf(stderr, "Screenlock starting
");
-
-	XkbSetDetectableAutoRepeat(dpy, True, NULL);
-	screen = XDefaultScreen(dpy);
-	XSync(dpy, 0);
-	syncstate();
-	lockscreen(dpy, screen, target == StateNoInputNoScreen || target == StateSuspend);
-	if ((target == StateNoInputNoScreen) || (target == StateSuspend)) {
-		state = StateNoInputNoScreen;
-		syncstate();
-	}
-	if (target == StateSuspend) {
-		state = StateSuspend;
-		syncstate();
-	}
-	readinputloop(dpy, screen);
-	if (wakeinterval) {
-		ioctl(rtc_fd, RTC_AIE_OFF, 0);
-		close(rtc_fd);
-	}
-	fprintf(stderr, "Screenlock terminating normally
");
-	return 0;
-}
diff --git a/scripts/core/sxmo_appmenu.sh b/scripts/core/sxmo_appmenu.sh
index 9d9ae74..99b6482 100755
--- a/scripts/core/sxmo_appmenu.sh
+++ b/scripts/core/sxmo_appmenu.sh
@@ -161,9 +161,9 @@ programchoicesinit() {
 	elif echo "$WMCLASS" | grep -i "power"; then
 		# Power menu
 		CHOICES="
-			$icon_lck Lock               ^ 0 ^ sxmo_lock.sh
-			$icon_lck Lock (Screen off)  ^ 0 ^ sxmo_lock.sh --screen-off
-			$icon_zzz Suspend            ^ 0 ^ sxmo_lock.sh --suspend
+			$icon_lck Lock               ^ 0 ^ sxmo_screenlock.sh lock && sxmo_unlocklistener.sh
+			$icon_lck Lock (Screen off)  ^ 0 ^ sxmo_screenlock.sh off && sxmo_unlocklistener.sh
+			$icon_zzz Suspend            ^ 0 ^ sxmo_screenlock.sh crust
 			$icon_out Logout             ^ 0 ^ pkill -9 dwm
 			$icon_rld Reboot             ^ 0 ^ st -e sudo reboot
 			$icon_pwr Poweroff           ^ 0 ^ st -e sudo poweroff
diff --git a/scripts/core/sxmo_common.sh b/scripts/core/sxmo_common.sh
index ffd4934..63d44fe 100644
--- a/scripts/core/sxmo_common.sh
+++ b/scripts/core/sxmo_common.sh
@@ -19,6 +19,10 @@ export LOGDIR="$XDG_DATA_HOME"/sxmo/modem
 export CONTACTFILE="$XDG_CONFIG_HOME/sxmo/contacts.tsv"
 # shellcheck disable=SC2034
 export MODEMSTATEFILE="$XDG_RUNTIME_DIR/sxmo.modem.state"
+# shellcheck disable=SC2034
+export UNSUSPENDREASONFILE="$XDG_RUNTIME_DIR/sxmo.suspend.reason"
+# shellcheck disable=SC2034
+export LASTSTATE="$XDG_RUNTIME_DIR/sxmo.suspend.laststate"
 
 command -v "$KEYBOARD" > /dev/null || export KEYBOARD=svkbd-mobile-intl
 
diff --git a/scripts/core/sxmo_inputhandler.sh b/scripts/core/sxmo_inputhandler.sh
index 936cbf0..9bd190c 100755
--- a/scripts/core/sxmo_inputhandler.sh
+++ b/scripts/core/sxmo_inputhandler.sh
@@ -153,7 +153,7 @@ if [ "$HANDLE" -ne 0 ]; then
 			sxmo_appmenu.sh sys
 			;;
 		"volup_three")
-			sxmo_lock.sh
+			sxmo_screenlock.sh crust
 			;;
 		"voldown_one")
 			xdotool key --clearmodifiers Alt+space
@@ -174,7 +174,7 @@ if [ "$HANDLE" -ne 0 ]; then
 			sxmo_appmenu.sh scripts &
 			;;
 		"bottomleftcorner")
-			sxmo_lock.sh &
+			sxmo_screenlock.sh off &
 			;;
 		"bottomrightcorner")
 			sxmo_rotate.sh &
diff --git a/scripts/core/sxmo_screenlock.sh b/scripts/core/sxmo_screenlock.sh
new file mode 100755
index 0000000..04a2126
--- /dev/null
+++ b/scripts/core/sxmo_screenlock.sh
@@ -0,0 +1,130 @@
+#!/usr/bin/env sh
+
+# include common definitions
+# shellcheck source=scripts/core/sxmo_common.sh
+. "$(dirname "$0")/sxmo_common.sh"
+
+# Run xinput and get touchscreen id
+TOUCHSCREEN_ID=8
+VOLKEY_ID=7
+POWER_ID=9
+
+REDLED_PATH="/sys/class/leds/red:indicator/brightness"
+BLUELED_PATH="/sys/class/leds/blue:indicator/brightness"
+
+# POWERBUTTON="/dev/input/event0"
+# UPVOL="/dev/input/event4"
+# DOWNVOL="/dev/input/event4"
+
+getCurState() {
+    blue="$(cat "$BLUELED_PATH")"
+    red="$(cat "$REDLED_PATH")"
+
+    if [ "$blue" = "0" ] && [ "$red" = "0" ] ; then
+        echo "unlock"
+    elif [ "$blue" = "0" ] && [ "$red" = "1" ] ; then
+        echo "crust"
+    elif [ "$blue" = "1" ] && [ "$red" = "0" ] ; then
+        echo "lock"
+    elif [ "$blue" = "1" ] && [ "$red" = "1" ] ; then
+        echo "off"
+    fi
+}
+
+if [ "$1" = "lock" ] ; then
+    # always echo last state first so that user can use it in their hooks
+    # TODO: Document LASTSTATE
+    getCurState > "$LASTSTATE"
+    # Do we want this hook after disabling all the input devices so users can enable certain devices?
+    if [ -x "$XDG_CONFIG_HOME/sxmo/hooks/lock" ]; then
+	      "$XDG_CONFIG_HOME/sxmo/hooks/lock"
+    fi
+
+    # TODO: Could be improved by running xinput and disabling ALL input devices automatically but would need
+    # to decide on the hook issues. Do we want a prelock and postlock? Or should users
+    # be expected to edit the source code for disabling certain input devices?
+    # this code allows us to not use the slock locking mechanism in the original sxmo_lock.sh
+    # when combined with a working slock (see ~iv's) implementation, this should be secure.
+    xinput disable "$TOUCHSCREEN_ID"
+    xinput disable "$VOLKEY_ID"
+    xinput disable "$POWER_ID"
+    killall lisgd
+
+    echo 0 > "$REDLED_PATH"
+    echo 1 > "$BLUELED_PATH"
+    exit 0
+elif [ "$1" = "unlock" ] ; then
+    getCurState > "$LASTSTATE"
+    if [ -x "$XDG_CONFIG_HOME/sxmo/hooks/unlock" ]; then
+	      "$XDG_CONFIG_HOME/sxmo/hooks/unlock"
+    fi
+
+    xset dpms force on
+    xinput enable "$TOUCHSCREEN_ID"
+    xinput enable "$VOLKEY_ID"
+    xinput enable "$POWER_ID"
+    sxmo_lisgdstart.sh
+
+    echo 0 > "$REDLED_PATH"
+    echo 0 > "$BLUELED_PATH"
+    exit 0
+elif [ "$1" = "off" ] ; then
+    getCurState > "$LASTSTATE"
+    # TODO: document this hook
+    if [ -x "$XDG_CONFIG_HOME/sxmo/hooks/screenoff" ]; then
+	      "$XDG_CONFIG_HOME/sxmo/hooks/screenoff"
+    fi
+
+    xset dpms force off
+    # stop responding to input
+    xinput disable "$TOUCHSCREEN_ID"
+    xinput disable "$VOLKEY_ID"
+    xinput disable "$POWER_ID"
+    killall lisgd
+
+    echo 1 > "$REDLED_PATH"
+    echo 1 > "$BLUELED_PATH"
+    exit 0
+elif [ "$1" = "crust" ] ; then
+    getCurState > "$LASTSTATE"
+
+    if [ -x "$XDG_CONFIG_HOME/sxmo/hooks/presuspend" ]; then
+	      "$XDG_CONFIG_HOME/sxmo/hooks/presuspend"
+    fi
+
+    # configure crust
+    # Do I need to unbind? https://git.sr.ht/~mil/sxmo-utils/commit/bcf4f5c24968df0055d15a9fca649f67de9ced6a
+    echo "deep" > /sys/power/mem_sleep # deep sleep
+
+    echo 1 > "$REDLED_PATH"
+    echo 0 > "$BLUELED_PATH"
+
+    echo "mem" > /sys/power/state
+
+    if [ -x "$XDG_CONFIG_HOME/sxmo/hooks/postwake" ]; then
+	      "$XDG_CONFIG_HOME/sxmo/hooks/postwake"
+    fi
+
+    # all we know is it's not the rtc. Maybe modem?
+    # TODO: Check mmcli or something or sxmo's notifs when
+    # https://gitlab.freedesktop.org/mobile-broadband/ModemManager/-/issues/356
+    # https://gitlab.com/postmarketOS/pmaports/-/merge_requests/2066
+    # fixed
+    # TODO: Document UNSUSPENDREASONFILE
+    echo "nonrtc" > "$UNSUSPENDREASONFILE"
+    getCurState > "$LASTSTATE"
+
+    echo 0 > "$REDLED_PATH"
+    echo 0 > "$BLUELED_PATH"
+    exit 0
+elif [ "$1" = "rtc" ] ; then
+    # USER MUST USE sxmo_screenlock.sh rtc rather than using rtcwake directly.
+    # With this new version of lock, we dont check the exit code of the user hook. User must execute "sxmo_screenlock.sh rtc $TIME" at the end of their hook (depending on whether they want to re-rtc)
+    echo 1 > "$REDLED_PATH"
+    echo 0 > "$BLUELED_PATH"
+    rtcwake -m mem -s "$2" && echo "rtc" > "$UNSUSPENDREASONFILE" && echo "crust" > "$LASTSTATE" && echo 0 > "$REDLED_PATH" && echo 0 > "$BLUELED_PATH" && "$XDG_CONFIG_HOME/sxmo/hooks/rtcwake"
+fi
+
+
+echo "usage: sxmo_screenlock.sh [lock|unlock|off|crust|rtc]"
+
diff --git a/scripts/core/sxmo_unlocklistener.sh b/scripts/core/sxmo_unlocklistener.sh
new file mode 100755
index 0000000..919f357
--- /dev/null
+++ b/scripts/core/sxmo_unlocklistener.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env sh
+
+# include common definitions
+# shellcheck source=scripts/core/sxmo_common.sh
+. "$(dirname "$0")/sxmo_common.sh"
+
+inotifywait --format %w /dev/input/event0 | while read file; do
+    sxmo_screenlock.sh unlock
+done