-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathutils.js
More file actions
303 lines (263 loc) · 10.3 KB
/
Copy pathutils.js
File metadata and controls
303 lines (263 loc) · 10.3 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
/*
* Customised Workspaces extension for Gnome 3
* This file is part of the Customised Workspaces Gnome Extension for Gnome 3
* Copyright (C) http://github.com/blipk
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// External imports
import Gio from "gi://Gio"
import GLib from "gi://GLib"
import { gettext as _ } from "resource:///org/gnome/shell/extensions/extension.js"
// Internal imports
import * as dev from "./dev.js"
export function textFormatter( text, options = {/*length: 50*/ } ) {
text = _( text )
if ( isEmpty( text ) ) return text
if ( options.length ) text = truncateString( text, options.length )
return text
}
export const textToKebabCase = str => str.replace( /[A-Z]/g, letter => `-${letter.toLowerCase()}` ).replace( /^[\-]+|[\-]+$/g, "" )
export const textToPascalCase = str => str.split( "-" ).map( word => word.charAt( 0 ).toUpperCase() + word.slice( 1 ).toLowerCase() ).join( "" )
//General
export function truncateString( instring, length = 50 ) {
let shortened = instring.replace( /\s+/g, " " )
if ( shortened.length > length )
shortened = shortened.substring( 0, length - 1 ) + "..."
return shortened
}
const special = [
"zeroth",
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelvth",
"thirteenth",
"fourteenth",
"fifteenth",
"sixteenth",
"seventeenth",
"eighteenth",
"nineteenth"
]
const deca = [
"twent",
"thirt",
"fourt",
"fift",
"sixt",
"sevent",
"eight",
"ninet"
]
export function stringifyNumber( n ) {
n = parseInt( n )
if ( n < 20 ) return special[n]
if ( n % 10 === 0 ) return deca[Math.floor( n / 10 ) - 2] + "ieth"
return deca[Math.floor( n / 10 ) - 2] + "y-" + special[n % 10]
}
export function isEmpty ( v ) {
return typeof v === "undefined" ? true
: v === null ? true
: Array.isArray( v ) && v.length === 0 ? true
: typeof v === "object" ? ( Object.getOwnPropertyNames( v ).length > 0 ? false : true )
: typeof v === "string" ? ( v.length > 0 ? false : true )
: Boolean( v )
}
export function forEachEntry( obj, callback, thisArg, recursive = false, recursiveIndex = 0 ) {
if ( obj === null ) throw new TypeError( "Not an object" )
thisArg = thisArg || obj
Object.entries( obj ).forEach( function ( entryArray, entryIndex ) {
let [ key, value ] = entryArray
let entryObj = { [key]: obj[key] }
let retIndex = entryIndex + recursiveIndex
callback.call( thisArg, key, obj[key], retIndex, entryObj, entryArray, obj )
if ( typeof obj[key] === "object" && obj[key] !== null && recursive === true ) {
if ( Array.isArray( obj[key] ) === true ) {
obj[key].forEach( function ( prop, index ) {
if ( Array.isArray( obj[key][index] ) === false && typeof obj[key][index] === "object" && obj[key][index] !== null ) {
recursiveIndex += Object.keys( obj ).length - 1
forEachEntry( obj[key][index], callback, thisArg, recursive, recursiveIndex )
}
} )
} else {
recursiveIndex += Object.keys( obj ).length - 1
forEachEntry( obj[key], callback, thisArg, recursive, recursiveIndex )
}
}
} )
}
export function filterObj( obj, predicate ) {
return Object.fromEntries( Object.entries( obj ).filter( predicate ) )
}
export function splitURI( inURI ) {
try {
let regexPattern = /^(([^:/\?#]+):)?(\/\/([^/\?#]*))?([^\?#]*)(\?([^#]*))?(#(.*))?/
let re = RegExp( regexPattern )
let output = re.exec( inURI )
if ( output[3] == undefined )
inURI = "foo://" + inURI
output = re.exec( inURI )
// Named capture groups not working on gjs :(
let splitURI = {
"scheme" : output[1], "schemeTrim" : output[2],
"authority" : output[3], "authorityTrim" : output[4],
"path" : output[5],
"query" : output[6], "queryTrim" : output[7],
"fragment" : output[8], "fragmentTrim" : output[9]
}
if ( splitURI["scheme"] == "foo:" )
splitURI["scheme"] = ""
inURI = inURI.substring( 6 )
return splitURI
} catch ( e ) { dev.log( e ) }
}
// Combines the benefits of spawn_sync (easy retrieval of output)
// with those of spawn_async (non-blocking execution).
// Based on https://github.com/optimisme/gjs-examples/blob/master/assets/spawn.js.
// https://github.com/p-e-w/argos/blob/master/argos%40pew.worldwidemann.com/utilities.js
export function spawnWithCallback( workingDirectory, argv, envp, flags, childSetup, callback ) {
let [
success,
pid,
stdinFile,
stdoutFile,
stderrFile
] = GLib.spawn_async_with_pipes( workingDirectory, argv, envp, flags, childSetup )
if ( !success )
return
GLib.close( stdinFile )
let standardOutput = ""
let standardError = ""
let stdoutStream = new Gio.DataInputStream( {
base_stream: new Gio.UnixInputStream( { fd: stdoutFile } )
} )
let stderrStream = new Gio.DataInputStream( {
base_stream: new Gio.UnixInputStream( { fd: stderrFile } )
} )
let stdoutDone = false
let stderrDone = false
const checkDone = () => {
if ( stdoutDone && stderrDone ) {
if ( standardError ) dev.log( "spawnWithCallback stderr:", standardError )
callback( standardOutput )
}
}
readStream( stdoutStream, function ( output ) {
if ( output === null ) {
stdoutStream.close( null )
stdoutDone = true
checkDone()
} else {
standardOutput += output
}
} )
readStream( stderrStream, function ( output ) {
if ( output === null ) {
stderrStream.close( null )
stderrDone = true
checkDone()
} else {
standardError += output
}
} )
}
export function readStream( stream, callback ) {
stream.read_line_async( GLib.PRIORITY_LOW, null, function ( source, result ) {
let [line] = source.read_line_finish( result )
if ( line === null ) {
callback( null )
} else {
callback( new TextDecoder().decode( line ) + "\n" )
readStream( source, callback )
}
} )
}
// these imports are required for the eval() usage in InjectionHandler.add()
import * as workspace from "resource:///org/gnome/shell/ui/workspace.js"
import * as workspaceAnimation from "resource:///org/gnome/shell/ui/workspaceAnimation.js"
import * as workspacesView from "resource:///org/gnome/shell/ui/workspacesView.js"
import * as workspaceThumbnail from "resource:///org/gnome/shell/ui/workspaceThumbnail.js"
import * as popupMenu from "resource:///org/gnome/shell/ui/popupMenu.js"
import * as background from "resource:///org/gnome/shell/ui/background.js"
import * as layout from "resource:///org/gnome/shell/ui/layout.js"
import * as overview from "resource:///org/gnome/shell/ui/overview.js"
import * as overviewControls from "resource:///org/gnome/shell/ui/overviewControls.js"
import { InjectionManager } from "resource:///org/gnome/shell/extensions/extension.js"
export class InjectionHandler {
constructor() {
this.injections = new Map()
this.manager = new InjectionManager()
}
add( prototype, methodName, createOverrideFunc ) {
try {
let savedProtoMethods = this.injections.get( prototype )
if ( !savedProtoMethods ) {
savedProtoMethods = new Map()
this.injections.set( prototype, savedProtoMethods )
}
savedProtoMethods.set( methodName, [createOverrideFunc, prototype[methodName].bind( {} )] )
this.manager.overrideMethod( prototype, methodName, createOverrideFunc )
} catch ( e ) { dev.log( e ) }
}
removeAll() {
try {
for ( let [prototype, savedProtoMethods] of this.injections.entries() )
for ( let methodName of savedProtoMethods.keys() )
this.manager.restoreMethod( prototype, methodName )
} catch ( e ) { dev.log( e ) }
}
destroy() {
try {
this.removeAll()
} catch ( e ) { dev.log( e ) }
}
}
export class SignalHandler {
constructor() {
this.signalIds = new Map()
}
add( target, signal = null, fn = null ) {
try {
let signalId = target.connect ? target.connect( signal, fn ) : target
this.signalIds.set( signalId, target )
} catch ( e ) { dev.log( e ) }
}
disconnectAll() {
try {
this.signalIds.forEach( ( target, id ) => target.disconnect ? target.disconnect( id ) : GLib.Source.remove( id ) )
this.signalIds.clear()
} catch ( e ) { dev.log( e ) }
}
destroy() {
try {
this.disconnectAll()
} catch ( e ) { dev.log( e ) }
}
}