Skip to content

Commit

Permalink
Merge pull request #11 from zba/master
Browse files Browse the repository at this point in the history
settings, center window,  works now
  • Loading branch information
e3rd authored May 22, 2018
2 parents 771cf11 + 8c75e98 commit 903f4e3
Show file tree
Hide file tree
Showing 6 changed files with 257 additions and 43 deletions.
143 changes: 143 additions & 0 deletions convenience.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/* -*- mode: js; js-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
Copyright (c) 2011-2012, Giovanni Campagna <scampa.giovanni@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of the GNOME nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
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 HOLDER 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.
*/
const GIRepository = imports.gi.GIRepository;
GIRepository.Repository.prepend_search_path("/usr/lib/gnome-shell");
GIRepository.Repository.prepend_library_path("/usr/lib/gnome-shell");
const Gettext = imports.gettext;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;

const Config = imports.misc.config;
const ExtensionUtils = imports.misc.extensionUtils;

/**
* initTranslations:
* @domain: (optional): the gettext domain to use
*
* Initialize Gettext to load translations from extensionsdir/locale.
* If @domain is not provided, it will be taken from metadata['gettext-domain']
*/
function initTranslations(domain) {
let extension = ExtensionUtils.getCurrentExtension();

domain = domain || extension.metadata['gettext-domain'];

// check if this extension was built with "make zip-file", and thus
// has the locale files in a subfolder
// otherwise assume that extension has been installed in the
// same prefix as gnome-shell
let localeDir = extension.dir.get_child('locale');
if (localeDir.query_exists(null))
Gettext.bindtextdomain(domain, localeDir.get_path());
// else
// Gettext.bindtextdomain(domain, Config.LOCALEDIR);
}

/**
* getSettings:
* @schema: (optional): the GSettings schema id
*
* Builds and return a GSettings schema for @schema, using schema files
* in extensionsdir/schemas. If @schema is not provided, it is taken from
* metadata['settings-schema'].
*/
function getSettings(schema) {
let extension = ExtensionUtils.getCurrentExtension();

schema = schema || extension.metadata['settings-schema'];

const GioSSS = Gio.SettingsSchemaSource;

// check if this extension was built with "make zip-file", and thus
// has the schema files in a subfolder
// otherwise assume that extension has been installed in the
// same prefix as gnome-shell (and therefore schemas are available
// in the standard folders)
let schemaDir = extension.dir.get_child('schemas');
let schemaSource;
if (schemaDir.query_exists(null))
schemaSource = GioSSS.new_from_directory(schemaDir.get_path(),
GioSSS.get_default(),
false);
else
schemaSource = GioSSS.get_default();

let schemaObj = schemaSource.lookup(schema, true);
if (!schemaObj)
throw new Error('Schema ' + schema + ' could not be found for extension '
+ extension.metadata.uuid + '. Please check your installation.');

return new Gio.Settings({ settings_schema: schemaObj });
}


function getSchemaData(schema) {
let extension = ExtensionUtils.getCurrentExtension();

schema = schema || extension.metadata['settings-schema'];

const GioSSS = Gio.SettingsSchemaSource;

// check if this extension was built with "make zip-file", and thus
// has the schema files in a subfolder
// otherwise assume that extension has been installed in the
// same prefix as gnome-shell (and therefore schemas are available
// in the standard folders)
let schemaDir = extension.dir.get_child('schemas');
let schemaSource;
if (schemaDir.query_exists(null))
schemaSource = GioSSS.new_from_directory(schemaDir.get_path(),
GioSSS.get_default(),
false);
else
schemaSource = GioSSS.get_default();

let schemaObj = schemaSource.lookup(schema, true);
if (!schemaObj)
throw new Error('Schema ' + schema + ' could not be found for extension '
+ extension.metadata.uuid + '. Please check your installation.');

const Settings = new Gio.Settings({ settings_schema: schemaObj });
const basicTypes = ["b", "y", "n", "q", "i", "u", "x", "t", "h", "d", "s", "o", "g", "?"].map(function(type){return {type: type, vt : new GLib.VariantType(type)}});
const allKeys = schemaObj.list_keys().map(function(keyName) {
const key = schemaObj.get_key(keyName);
const keyType = key.get_value_type();
const keyTypeFound = basicTypes.find(bt=>keyType.equal(bt.vt));
if (!keyTypeFound) {return null;}
const summary = key.get_summary();
const description = key.get_description();
const defaultValue = key.get_default_value().unpack();
const value = Settings.get_value(keyName).unpack();
return {name: keyName, summary: summary, description: description, defaultValue: defaultValue, value: value, type: keyTypeFound.type }

}).filter(a=>Boolean(a));
return {basicSchema: allKeys, settings: Settings};
}




118 changes: 75 additions & 43 deletions extension.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@ const Mainloop = imports.mainloop;
const Meta = imports.gi.Meta;
const Lang = imports.lang;
const Shell = imports.gi.Shell;
const Me = imports.misc.extensionUtils.getCurrentExtension();
const Convenience = Me.imports.convenience;
const Gdk = imports.gi.Gdk

function log() {
// global.log.apply(null, arguments);
}
const KeyManager = new Lang.Class({ // based on https://superuser.com/questions/471606/gnome-shell-extension-key-binding/1182899#1182899
Name: 'MyKeyManager',

KeyManager = new Lang.Class({ // based on https://superuser.com/questions/471606/gnome-shell-extension-key-binding/1182899#1182899
Name: 'MyKeyManager',

_init: function() {
this.grabbers = new Map()

Expand All @@ -20,9 +26,9 @@ KeyManager = new Lang.Class({ // based on https://superuser.com/questions/471606
},

listenFor: function(accelerator, callback){

log('Trying to listen for hot key [accelerator={}]', accelerator)
let action = global.display.grab_accelerator(accelerator)
let action = global.display.grab_accelerator(accelerator)
log("action:")
log(action)

Expand All @@ -32,11 +38,11 @@ KeyManager = new Lang.Class({ // based on https://superuser.com/questions/471606
log('Grabbed accelerator [action={}]', action)
let name = Meta.external_binding_name_for_action(action)
log('Received binding name for action [name={}, action={}]',
name, action)
name, action)

log('Requesting WM to allow binding [name={}]', name)
Main.wm.allowKeybinding(name, Shell.ActionMode.ALL)

this.grabbers.set(action, {
name: name,
accelerator: accelerator,
Expand All @@ -59,40 +65,42 @@ KeyManager = new Lang.Class({ // based on https://superuser.com/questions/471606
});


Controller = new Lang.Class({ // based on https://superuser.com/questions/471606/gnome-shell-extension-key-binding/1182899#1182899
const Controller = new Lang.Class({ // based on https://superuser.com/questions/471606/gnome-shell-extension-key-binding/1182899#1182899
Name: 'MyController',

//This is a javascript-closure which will return the event handler
//for each hotkey with it's id. (id=1 For <Super>+1 etc)
jumpapp: function(shortcut) {
function _prepare(s) {
if(s.substr(0,1) === "/" && s.slice(-1) === "/") {
return [new RegExp(s.substr(1, s.length-2)), "search"];
return [new RegExp(s.substr(1, s.length-2)), "search"];
}
else {
return [s, "indexOf"];
}
}
return function() {
var launch = shortcut[1].trim();
var wm_class, wmFn, title, titleFn;

return function() {
var launch = shortcut[1].trim();
var wm_class, wmFn, title, titleFn;
[wm_class, wmFn] = _prepare(shortcut[2].trim());
[title, titleFn] = _prepare(shortcut[3].trim());
[title, titleFn] = _prepare(shortcut[3].trim());

let seen = 0;

let is_conforming = function(wm) {
var window_class = wm.get_wm_class() || '';
var window_title = wm.get_title() || '';
// check if the current window is conforming to the search criteria
if(wm_class) { // seek by class
// wm_class AND if set, title must match
if((wm.get_wm_class()[wmFn](wm_class) > -1 && (!title || wm.get_title()[titleFn](title) > -1))) {
if(window_class[wmFn](wm_class) > -1 && (!title || window_title[titleFn](title) > -1)) {
return true;
}
} else if( (title && (wm.get_title()[titleFn](title) > -1) ) || // seek by title
(!title && ((wm.get_wm_class().toLowerCase().indexOf(launch.toLowerCase()) > -1) || // seek by launch-command in wm_class
(wm.get_title().toLowerCase().indexOf(launch.toLowerCase()) > -1))) // seek by launch-command in title
) {
} else if( (title && window_title[titleFn](title) > -1 ) || // seek by title
(!title && ((window_class.toLowerCase().indexOf(launch.toLowerCase()) > -1) || // seek by launch-command in wm_class
(window_title.toLowerCase().indexOf(launch.toLowerCase()) > -1))) // seek by launch-command in title
) {
return true;
}
return false;
Expand All @@ -114,52 +122,62 @@ Controller = new Lang.Class({ // based on https://superuser.com/questions/471606
}
}
if(seen) {
seen.get_workspace().activate_with_focus(seen, true);
seen.activate(0);
if (!wm.has_focus()) {
log('no focus, go to:' + wm.get_wm_class());
focusWindow(seen);
} else if (settings.get_boolean('switch-back-when-focused')) {
window_monitor = wm.get_monitor();
const window_list = global.display.get_tab_list(0, null).filter(w=>w.get_monitor() === window_monitor && w !== wm);
lastWindow = window_list[0];
if (lastWindow) {
log('focus, go to:' + lastWindow.get_wm_class());
focusWindow(lastWindow);
}
}
} else {
imports.misc.util.spawnCommandLine(launch);
}
return;
}
},

enable: function() {
enable: function() {
try {
var s = Shell.get_file_contents_utf8_sync(confpath);
}
catch(e) {
log("Run or raise: can't load confpath" + confpath + ", creating new file from default");
log("Run or raise: can't load confpath" + confpath + ", creating new file from default");
imports.misc.util.spawnCommandLine("cp " + defaultconfpath + " " + confpath);
try {
var s = Shell.get_file_contents_utf8_sync(defaultconfpath); // it seems confpath file is not ready yet, reading defaultconfpath
}
catch(e) {
log("Run or raise: Failed to create default file")
return;
}
}
}
this.shortcuts = s.split("\n");
this.shortcuts = s.split("\n");
this.keyManager = new KeyManager();

for(let line of this.shortcuts) {
try {
if(line[0] == "#" || line.trim() == "") {
continue;
}
let s = line.split(",")
if(s.length > 2) { // shortcut, launch, wm_class, title
if(line[0] == "#" || line.trim() == "") {
continue;
}
let s = line.split(",")
if(s.length > 2) { // shortcut, launch, wm_class, title
this.keyManager.listenFor(s[0].trim(), this.jumpapp(s))
} else { // shortcut, command
this.keyManager.listenFor(s[0].trim(), function() {imports.misc.util.spawnCommandLine(s[1].trim())})
}
}

} catch(e) {
log("Run or raise: can't parse line: " + line)
}
}
}
},

disable: function() {
disable: function() {
for (let it of this.keyManager.grabbers) {
try {
global.display.ungrab_accelerator(it[1].action)
Expand All @@ -168,19 +186,20 @@ Controller = new Lang.Class({ // based on https://superuser.com/questions/471606
catch(e) {
log("Run or raise: error removing keybinding " + it[1].name)
log(e)
}
}
}
}

}


});

var app, confpath, defaultconfpath;
var app, confpath, defaultconfpath, settings;

function init(settings) {
confpath = settings.path + "/shortcuts.conf";
defaultconfpath = settings.path + "/shortcuts.default";
function init(options) {
confpath = options.path + "/shortcuts.conf";
defaultconfpath = options.path + "/shortcuts.default";
app = new Controller();
settings = Convenience.getSettings();
}

function enable(settings) {
Expand All @@ -190,3 +209,16 @@ function enable(settings) {
function disable() {
app.disable();
}

function focusWindow(wm) {
wm.get_workspace().activate_with_focus(wm, true);
wm.activate(0);
if (settings.get_boolean('center-mouse-to-focused-window')) {
const display = Gdk.Display.get_default();//wm.get_display();
const deviceManager = display.get_device_manager();
const pointer = deviceManager.get_client_pointer();
const screen = pointer.get_position()[0];
const center = wm.get_center();
pointer.warp(screen,center.x, center.y);
}
}
1 change: 1 addition & 0 deletions metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
],
"url": "https://github.com/CZ-NIC/run-or-raise",
"uuid": "run-or-raise@edvard.cz",
"settings-schema": "org.gnome.shell.extensions.run-or-raise",
"version": 0.9
}
Loading

0 comments on commit 903f4e3

Please sign in to comment.