-
Notifications
You must be signed in to change notification settings - Fork 2
/
Misc.j
276 lines (232 loc) · 8.55 KB
/
Misc.j
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
/*
This file is part of FrACT10, a vision test battery.
Copyright © 2021 Michael Bach, [email protected], <https://michaelbach.de>
Misc.j
*/
@import <Foundation/Foundation.j>
@import <AppKit/AppKit.j>
@import "Settings.j"
/**
A collection of "miscellaneous" functions.
All are class variables for easy global access.
*/
@implementation Misc: CPObject {
}
/**
Delay for seconds
*/
function _pause(ms) { //console.info("Misc>_pause");
return new Promise(resolve => setTimeout(resolve, ms));
}
+ (async void) asyncDelaySeconds: (float) secs { //console.info("Misc>delaySeconds");
await _pause(secs * 1000);
}
/**
Return random integer from 0 to i-1 */
+ (int) iRandom: (int) i {
return Math.floor(Math.random() * i);
}
/**
Limit the input value to lie between 0 and 1
*/
+ (float) limit01: (float) theValue {
return [self limit: theValue lo: 0 hi: 1];
}
/**
Limit the input value to lie between 2 values
*/
+ (float) limit: (float) theValue lo: (float) lo hi: (float) hi { // limit the input value to lie between lo and hi
if (theValue < lo) return lo;
if (theValue > hi) return hi;
return theValue;
}
+ (BOOL) isOdd: (int) i {
return (i & 1);
}
/**
Handle fullscreen. That was quite difficult to figure out :) (at that time…).
*/
// https://hacks.mozilla.org/2012/01/using-the-fullscreen-api-in-web-browsers/
+ (BOOL) isFullScreenSupported {
return (
document.fullscreenEnabled || document.webkitFullscreenEnabled ||
document.mozFullScreenEnabled || document.msFullscreenEnabled
);
}
+ (BOOL) isFullScreen {
if (![self isFullScreenSupported]) return NO;
return !!(document.fullscreenElement || document.webkitFullscreenElement ||
document.mozFullScreenElement || document.msFullscreenElement);
}
+ (void) fullScreenOn: (BOOL) onOff {
if (![self isFullScreenSupported]) return;
if ([self isFullScreen] == onOff) return;
const element = document.documentElement;
if (onOff) {
if (element.requestFullscreen)
element.requestFullscreen();
else if(element.mozRequestFullScreen)
element.mozRequestFullScreen();
else if(element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
else if(element.msRequestFullscreen)
element.msRequestFullscreen();
} else {
if (document.exitFullscreen)
document.exitFullscreen();
else if(document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if(document.webkitExitFullscreen)
document.webkitExitFullscreen();
else if(document.msExitFullscreen)
document.msExitFullscreen();
}
}
+ (void) centerWindowOrPanel: (CPWindow) p {
[p setFrameOrigin: CGPointMake((window.innerWidth - 800) / 2, (window.innerHeight - 600) / 2)];
}
+ (void) copyString2ClipboardWithDialog: (CPString) s { //console.info("Misc>copyString2ClipboardWithDialog");
const alert = [CPAlert alertWithMessageText: "Done."
defaultButton: "Yes, put result → clipboard (ߵyߴ)" alternateButton: "Cancel (ߵcߴ)" otherButton: nil
informativeTextWithFormat: "\rShall we place the result details into the clipboard?\r\r(So you can paste them into a spreadsheet.)\r"];
[[alert buttons][0] setKeyEquivalent: "c"]; // the "Cancel" button selected by "c"
[[alert buttons][1] setKeyEquivalent: "y"]; // the "Yes" button selected by "n"
[alert setAlertStyle: CPInformationalAlertStyle];
[[alert window] setFrameOrigin: CGPointMake(200, 200)];
[alert runModalWithDidEndBlock: function(alert, returnCode) {
switch (returnCode) {
case 1: /*console.info("ok, dann nicht");*/ break;
case 0:
[self copyString2Clipboard: s];
[[CPNotificationCenter defaultCenter] postNotificationName: "buttonExportEnableYESorNO" object: 0];
break;
}
}];
}
/**
Utility to copy a string to the clipboard which surprisingly now works in all(?) modern browsers
*/
+ (void) copyString2Clipboard: (CPString) s { //console.info("Misc>copyString2Clipboard: ", s);
try {
navigator.clipboard.writeText(s); // only over https
}
catch(e) { // avoid the global error catcher
console.info("Error copying result to clipboard: ", e); // alert(e);
}
}
+ (CPString) date2YYYY_MM_DD: (CPDate) theDate {
return [CPString stringWithFormat:@"%04d-%02d-%02d", theDate.getFullYear(), theDate.getMonth() + 1, theDate.getDate()];
}
/**
ISO date formatter
*/
+ (CPString) date2HH_MM_SS: (CPDate) theDate {
return [CPString stringWithFormat:@"%02d:%02d:%02d", theDate.getHours(), theDate.getMinutes(), theDate.getSeconds()];
}
+ (CPString) stringFromInteger: (int) num { //console.info("Misc>stringFromInteger");
return [CPString stringWithFormat: @"%d", num];
}
+ (CPString) stringFromNumber: (float) num decimals: (int) decs localised: (BOOL) locd { //console.info("Misc>stringFromNumber");
if (decs < 1) return [self stringFromInteger: num];
const fmt = @"%6." + [CPString stringWithFormat:@"%d", decs] + "f";
let str = [CPString stringWithFormat: fmt, num];
while ([str hasPrefix:@" "] && [str length] > 1) {
str = [str substringFromIndex:1];
}
while ([str hasSuffix:@"00"]) {
str = [str substringToIndex:str.length-(str.length>0)];
}
if ([str hasSuffix:@"."]) str = str + "0";
if (locd && ([Settings decimalMarkChar] != ".")) {
str = [str stringByReplacingOccurrencesOfString:@"." withString:@","];
}
//console.info("Misc>stringFromNumber ", fmt, ", ", [Settings decimalMarkChar], " ,", str);
return str;
}
/**
Given an epsilon, we test for "equality" of 2 floating point numbers
*/
+ (BOOL) areNearlyEqual: (float)a and: (float) b {
const epsilon = 1e-9, diff = Math.abs(a - b), magnitude = Math.abs(a) + Math.abs(b);
return (diff / magnitude) < epsilon;
}
+ (void) makeFrameSquareFromWidth: (CPView) view {
const rect1 = [view frame];
[view setFrame: CGRectMake(rect1.origin.x, rect1.origin.y - (rect1.size.width - 16) / 2, rect1.size.width, rect1.size.width)];
}
/**
Helper function: Find out if a URL exists
*/
+ (BOOL) existsUrl: (CPString) url { //console.info("Misc>existsUrl");
let success = NO;
try {
let request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', url, NO);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be modified
success = (request.status != 404)
}
catch (e){
console.log(e);
}
if (!success) {
alert("The page you are trying to reach is not available (in this context).");
}
return success;
}
/* ///////////////////////////////////// OLD, not in use (yet) */
/*
+ (CPString) capitalizeFirstLetter: (CPString) s {
if (s.length < 1) return @"";
else if (s.length == 1) return [s capitalizedString];
const firstChar = [[s substringToIndex: 1] uppercaseString];
const otherChars = [s substringWithRange: CPMakeRange(1, s.length - 1)];
return firstChar + otherChars;
}
// formats a number to given precision
+ (CPString) rStrFromNumber: num precision: (int) precision {
if (isNaN(precision)) {
let precision=0;
}
if (precision <= 0) { // no decimal points
return String(Math.round(num));
}
//return String(Math.floor(num) + "." + Math.floor(num * Math.pow(10, precision)).toString().substr(-precision));//this is from Macromedia, but wrong all the same… 15.12.2003
let temp = Math.pow(10, precision);
temp = Math.round(num * temp) / temp;
return String(temp);
}
// formats a number to a “sensible” precision
static public function rStr(theValue:Number):String {
let precision:int=1,theValueAbs:Number=Math.abs(theValue);
if (theValueAbs < 0.0001) { // this could be easier using log10…
precision=7;
} else {
if (theValueAbs < 0.001) {
precision=6;
} else {
if (theValueAbs < 0.01) {
precision=5;
} else {
if (theValueAbs < 0.1) {
precision=4;
} else {
if (theValueAbs < 1.0) {
precision=3;
} else {
if (theValueAbs < 10.0) {
precision=2;
}
}
}
}
}
}
return rStrN(theValue, precision);
}
*/
@end