forked from brockgr/csshx
-
Notifications
You must be signed in to change notification settings - Fork 2
/
csshX
executable file
·3054 lines (2339 loc) · 90.7 KB
/
csshX
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
#!/usr/bin/perl
#==============================================================================#
# csshX -- Cluster SSH tool for Mac OS X Terminal.app #
#==============================================================================#
# Copyright 2011 by Gavin Brock <[email protected]> #
# #
# This program is free software; you may redistribute it and/or modify it #
# under the same terms as Perl itself. #
#==============================================================================#
use strict;
use warnings;
use version; (our $VERSION = '$Rev: 0.74-40-g3f4ae03$') =~ s/\$Rev:\s*(.*)\$/$1/;
my $config; # Global configuration object..
#==============================================================================#
package CsshX::Config;
use Getopt::Long;
use Socket;
use POSIX qw(uname);
use version;
use Scalar::Util qw(blessed);
# All possible config keys
my @config_keys = qw(
action_key
color_selected_foreground color_selected_background
color_disabled_foreground color_disabled_background
color_master_background color_master_foreground
color_setbounds_background color_setbounds_foreground
tile_x tile_y ssh_args no_growl hosts remote_command
config help launchpid login man master
master_height screen_bounds screen space debug
slave slavehost slaveid sock version osver
session_max ping_test ping_timeout ssh interleave
master_settings_set slave_settings_set
sorthosts clusters list_clusters bash_env
pause_ms
);
foreach my $prop (@config_keys) {
no strict 'refs';
*{"CsshX::Config::$prop"} = sub { $_[0]->{$prop} };
}
sub new {
my ($pack) = @_;
# Default config settings
bless my $obj = {
action_key => '\\001', # Ctrl-A
color_disabled_background => '',
color_disabled_foreground => '{37779,37779,37779}',
color_selected_background => '{17990,35209,53456}',
color_selected_foreground => '',
color_master_background => '{38036,0,0}',
color_master_foreground => '{65535,65535,65535}',
color_setbounds_background => '{17990,35209,53456}',
color_setbounds_foreground => '',
master_height => 87, # Pixels
screen => 0,
space => 0,
debug => 0,
tile_x => 0,
tile_y => 0,
ssh_args => '',
session_max => 256,
ping_test => '',
ping_timeout => 2,
ssh => 'ssh',
no_growl => 0,
interleave => 0,
hosts => [],
clusters => {},
pause_ms => 0
}, ref($pack) || $pack;
($obj->{osver} = (uname())[2]) =~ s/^(\d+)(\.\d+).*/"10.".($1-4)."$2"/e;
$obj->load_clusters("/etc/clusters");
$obj->load_csshrc($_) foreach ("/etc/csshrc", "$ENV{HOME}/.csshrc");
# Command line options - must map to config keys
GetOptions($obj,
'config|c=s@', 'login|l=s', 'master', 'slave',
'sock=s', 'slavehost=s', 'launchpid=s', 'slaveid=s',
'tile_x|x=i', 'tile_y|y=i', 'ping_test|ping', 'ping_timeout=i',
'screen=s', 'space=i', 'ssh_args=s', 'debug:+',
'session_max=i', 'help|h', 'man|m', 'version|v',
'ssh=s', 'hosts=s@', 'remote_command=s','no_growl',
'master_settings_set|mss=s', 'slave_settings_set|sss=s',
'interleave|i=i', 'sorthosts', 'list_clusters', 'bash_env',
'pause_ms|pm=i'
) || $obj->pod(-msg => "$0: bad usage\n");
# Load any extra configs specified in config file or command line
$obj->load_hosts($_) foreach @{$obj->{hosts}};
$obj->load_csshrc($_) foreach @{$obj->{config}};
if ($obj->{space} && ($obj->{osver} ge qv(10.7.0))) {
warn "space number not supported on 10.7 (Lion) or newer\n";
$obj->{space} = 0;
}
return $obj;
}
sub load_hosts {
my ($obj, $host_file) = @_;
open (my $fh,
$host_file eq "-" ? "<&STDIN" : "< $host_file"
) || die "Can't read [$host_file]: $!";
while (defined(my $line = <$fh>)) {
$line =~ s/#.*$//;
my ($name, $command) = ($line =~ m/(\S+)\s+(.*)/g);
next unless $name;
push @ARGV, CsshX::Host->new($name, $command);
}
}
sub load_clusters {
my ($obj, $config_file) = @_;
return unless -f $config_file;
open(my $fh, '<', $config_file ) || die "Can't read [$config_file]: $!";
while (defined(my $line = <$fh>)) {
$line =~ s/#.*$//;
my ($cluster, @hosts) = split /\s+/, $line;
next unless @hosts;
$obj->{clusters}->{$cluster} = \@hosts;
}
close($fh);
}
sub load_csshrc {
my ($obj, $config_file) = @_;
return unless -f $config_file;
my (@clusters, %settings);
open(my $fh, '<', $config_file ) || die "Can't read [$config_file]: $!";
while (defined(my $line = <$fh>)) {
$line =~ s/#.*$//;
if (my ($key, $value) = ($line =~ m/^\s*(\S+)\s*=\s*(.*?)\s*$/)) {
if ($key eq 'extra_cluster_file') {
$obj->load_clusters($_) foreach (
map { local $_ = $_; s/(~|\$HOME)/$ENV{HOME}/g; $_} split /\s*,\s*/, $value
);
} elsif ($key eq 'screen_bounds') {
my $bounds = $obj->parse_bounds($value);
$settings{$key} = $bounds if $bounds;
} elsif ($key eq 'clusters') {
push @clusters, split /\s+/, $value;
} else {
$settings{$key} = $value;
}
}
}
close($fh);
foreach my $cluster (@clusters) {
if (defined(my $cluster_hosts = $settings{$cluster})) {
$obj->{clusters}->{$cluster} = [split /\s+/, $cluster_hosts];
} else {
warn "No hosts defined for cluster [$cluster] in [$config_file]";
}
}
foreach my $key (@config_keys) {
$obj->{$key} = $settings{$key} if exists $settings{$key};
}
}
sub parse_bounds {
my ($obj,$value) = @_;
if ($value =~ /^\s*\{\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\}\s*$/) {
return [$1,$2,$3,$4];
}
}
sub parse_range {
my ($pat) = @_;
if ($pat =~ /,/) {
return map { parse_range($_) } split ',', $pat;
} elsif ($pat =~ /^([^-]+)-([^-]+)$/) {
return ($1..$2);
} else {
return $pat;
}
}
sub parse_netmask {
my ($host, $mask) = @_;
my $pack_host = inet_aton($host) || die "Bad hostname in mask [$host]";
my $pack_mask;
if ($mask =~ /^\d+$/) {
$pack_mask = pack 'N', (2**32 - 2**(32-$mask));
} else {
$pack_mask = inet_aton($mask) || die "Bad netmask [$mask]";
}
my $start = unpack('N', $pack_host);
my $end = unpack('N', &INADDR_BROADCAST ^ $pack_mask | $pack_host);
my @ips;
for (my $n=$start; $n<=$end; $n++) {
push @ips, inet_ntoa(pack('N', $n));
}
return @ips;
}
sub expand_hostrange {
my ($pat) = @_;
# 192.168.0.0/24
# 192.168.0.0/255.255.255.0
# 192.168.0.[0-255]
# 192.168.0.[0-20,13]
# 192.168.[0-2].[255,254]
# 192.168.[0-2].0/24
# 192.168.0.1+3
if ($pat =~ /^(.*)\+(\d+)$/) {
my $to_repeat = $1;
return [ map { $to_repeat } (1..$2) ];
}
my ($user, $host, $port) = CsshX::Process->parse_user_host_port($pat);
$user = $user ? "$user\@" : '';
$port = $port ? ":$port" : '';
if ($port =~ /^:\[(.+)\]$/) {
# Port range
return [ map { "$user$host:$_" } parse_range($1) ];
} elsif ($host =~ /^(.+)\/(.+)$/) {
# Looks like an IPv4 netmask
return [ map { "$user$_$port" } parse_netmask($1,$2) ];
} elsif ($host =~ /^(.*)\[(.*?)\](.*)$/) {
my $pre = $1; my $post = $3;
return [ map { "$user$pre$_$post$port" } parse_range($2) ];
}
}
sub all_hosts {
my ($obj) = @_;
my (@hosts, $ping, $ping_map);
if ($config->ping_test) {
# Load Net::Ping and dependencies only if needed
eval 'use Net::Ping; use Carp::Heavy; use Scalar::Util';
die "Can't ping_test: $@" if $@;
$ping = {};
$ping_map = {};
}
while (my $arg = shift @ARGV) {
if (my $clusthosts = $obj->{clusters}->{$arg}) {
print "Expand cluster: $arg => @$clusthosts\n" if $config->debug;
push @ARGV, @$clusthosts;
} elsif ((not blessed $arg) && (my $rangehosts = expand_hostrange($arg))) {
print "Expand host range: $arg => @$rangehosts\n" if $config->debug;
push @ARGV, @$rangehosts;
} else {
$arg = CsshX::Host->new($arg) unless ref $arg;
print "Host: $arg->{name}\n" if $config->debug;
if ($ping) {
my ($user, $host, $port) = CsshX::Process->parse_user_host_port($arg->name);
$port ||= getservbyname('ssh', 'tcp') || 22;
# We cannot identify 'ack's by port, so we have one ping object for each
unless ($ping->{$port}) {
$ping->{$port} = Net::Ping->new("syn", $config->ping_timeout);
$ping->{$port}->service_check(1);
$ping->{$port}->{port_num} = $port;
$ping_map->{$port} = {};
}
# Multiple user@host's may be used so map users to host,port
unless ($ping_map->{$port}->{$host}) {
$ping_map->{$port}->{$host} = [];
eval {
$ping->{$port}->ping("$host");
}; if ($@) {
if ($@ =~ /Too many open files/) {
# Handle a batch of pings to free file handles
push @hosts, process_pings($ping,$ping_map);
} else {
die "ping_test failed: $@";
}
}
}
push @{$ping_map->{$port}->{$host}}, $arg;
} else {
push @hosts, $arg;
if (@hosts > $config->session_max) {
die "Too many hosts. Use --session_max if you need more, ".
"or --ping_test to only connect to ones that are up";
}
}
}
}
if ($ping) {
push @hosts, process_pings($ping,$ping_map);
}
$obj->pod(-msg => "$0: Need at least one hostname or clustername\n")
unless @hosts;
return @hosts;
}
sub process_pings {
my ($ping, $ping_map) = @_;
my @hosts;
foreach my $port (keys %{$ping_map}) {
print "Ping Port: $port\n" if $config->debug;
while (my $host = $ping->{$port}->ack) {
my @args = @{$ping_map->{$port}->{$host}};
print "Ping Ack: $host (@args)\n" if $config->debug;
push @hosts, @args;
if (@hosts > $config->session_max) {
die "Too many hosts. Use --session_max if you need more";
}
}
}
%$ping_map = ();
%$ping = ();
return @hosts;
}
sub set {
my ($obj, $prop, $val) = @_;
$obj->{$prop} = $val;
}
sub pod {
shift;
eval "use Pod::Usage"; die $@ if $@;
pod2usage(@_)
}
#==============================================================================#
package CsshX::Host;
sub new {
my ($pkg, $name, $command) = @_;
bless my $obj = { name => $name }, ref($pkg) || $pkg;
$obj->{command} = $command if defined $command;
return $obj;
}
sub name { return $_[0]->{name}; }
sub command { return $_[0]->{command}; }
#==============================================================================#
package CsshX::Socket;
use base qw(IO::Socket::UNIX);
sub set_read_buffer { *{$_[0]}->{buf_read} = $_[1]; }
sub set_write_buffer { *{$_[0]}->{buf_write} = $_[1]; }
sub read_buffered {
my ($obj) = @_;
*$obj->{buf_read} = '' unless defined *$obj->{buf_read};
if ($obj->sysread(*$obj->{buf_read}, 1024, length *$obj->{buf_read})) {
return *$obj->{buf_read};
} else {
$obj->terminate;
}
}
sub write_buffered {
my ($obj) = @_;
if (my $bwrote = $obj->syswrite(*$obj->{buf_write}, 1024)) {
substr(*$obj->{buf_write},0,$bwrote,'');
return ! (length *$obj->{buf_write});;
} else {
$obj->terminate;
}
}
sub terminate { $_[0]->close; }
#==============================================================================#
package CsshX::Socket::Selectable;
use base qw(CsshX::Socket);
use IO::Select;
sub new {
my ($pack, @args) = @_;
if (my $obj = $pack->SUPER::new(@args)) {
*$obj->{readers} = IO::Select->new($obj);
*$obj->{writers} = IO::Select->new();
return $obj;
}
}
sub readers { *{$_[0]}->{readers} }
sub writers { *{$_[0]}->{writers} }
sub handle_io {
my ($obj) = @_;
my ($can_read, $can_write) = IO::Select::select($obj->readers, $obj->writers);
foreach my $reader (@$can_read) { $reader->can_read() }
foreach my $writer (@$can_write) { $writer->write_buffered &&
$obj->writers->remove($writer); }
}
sub terminate {
my ($obj) = @_;
$obj->writers->remove($obj);
$obj->readers->remove($obj);
$obj->SUPER::terminate();
}
#==============================================================================#
package CsshX::Window;
use base qw(IO::Handle);
# Define ScriptingBridge/AppKit objects that we will use
@NSWorkspace::ISA = @SBApplication::ISA = @NSScreen::ISA = @NSColor::ISA =
@NSEvent::ISA = @NSApplication::ISA =
qw(PerlObjCBridge);
my ($app,$terminal,$sysevents);
sub init {
eval "use Foundation; use List::Util qw(min max) "; die $@ if $@;
NSBundle->bundleWithPath_(
'/System/Library/Frameworks/ScriptingBridge.framework' # Loads AppKit too
)->load;
$app = NSApplication->sharedApplication();
$terminal = SBApplication->applicationWithBundleIdentifier_(
"com.apple.terminal"
);
$sysevents = SBApplication->applicationWithBundleIdentifier_(
"com.apple.SystemEvents"
);
Growl->init;
}
my ($cur_bounds, $max_bounds);
sub make_NSColor {
my ($obj, $str) = @_;
return $str if ref $str; # it's already an NSColor Obj
# Can create an nscolor in two formats
# { 65535, 65535, 65535 }
# FFFFFF
my ($r,$g,$b) = @_;
if ($str =~ /^\{(\d+),(\d+),(\d+)\}$/) {
($r,$g,$b) = map { $_ / 65535 } ($1,$2,$3);
} elsif ($str =~ /^(\w\w)(\w\w)(\w\w)$/) {
($r,$g,$b) = map { hex($_) / 255 } ($1,$2,$3);
} else {
die "Bad color [$str]";
}
return NSColor->colorWithCalibratedRed_green_blue_alpha_($r,$g,$b,0);
}
my $shell;
sub get_shell () {
return $shell if $shell; # Cached for speed
# Check Terminal.app settings
if (my $defs = NSUserDefaults->alloc->init) {
$defs->addSuiteNamed_("com.apple.terminal");
my $set = $defs->stringForKey_("Default Window Settings");
my $dict = $defs->dictionaryForKey_("Window Settings");
if ($set && $$set && $dict && $$dict) {
my $subdict = $dict->objectForKey_($set);
if ($subdict && $$subdict) {
my $shellStr = $subdict->objectForKey_("CommandString");
$shell = $shellStr->UTF8String if $shellStr && $$shellStr;
}
}
}
# else try the 'passwd' file
$shell ||= (getpwuid "$>")[8];
return $shell;
}
# Create an OSType (bid endian long) from a string
sub OSType ($) { return unpack('N', $_[0]) }
sub open_window {
my ($pack, @args) = @_;
# Quote the command arguments
my $cmd = join ' ', map { s/(["'])/\\$1/g; "'$_'" } @args;
# don't exec if debugging so we can see errors
unless ($config->debug) {
if (get_shell =~ /fish$/) {
$cmd = "clear; and exec $cmd"
} else {
$cmd = "clear && exec $cmd"
}
}
# Hide the command from any shell history
$cmd = 'history -d $(($HISTCMD-1)) && '.$cmd if get_shell =~ m{/(ba)?sh$};
# TODO - (t)csh, ksh, zsh
my $tabobj = $terminal->doScript_in_($cmd, undef) || return;
my $tty = $tabobj->tty->UTF8String || return;
my $windows = $terminal->windows;
for (my $n=0; $n<$windows->count; $n++) {
my $window = $windows->objectAtIndex_($n);
my $tabs = $window->tabs;
for (my $m=0; $m<$tabs->count; $m++) {
my $tab = $tabs->objectAtIndex_($m);
if ($tab->tty && ($tab->tty->UTF8String eq $tty)) {
my $obj = ref $pack ? $pack : $pack->SUPER::new();
$obj->set_windowid("".$window->id);
$obj->set_tabid($m);
return $obj;
}
}
}
}
sub set_windowid { *{$_[0]}->{windowid} = $_[1]; }
sub windowid { *{$_[0]}->{windowid}; }
sub set_tabid { *{$_[0]}->{tabid} = $_[1]; }
sub tabid { *{$_[0]}->{tabid}; }
sub uid { $_[0]->windowid.','. $_[0]->tabid }
sub winobj { $terminal->windows->objectWithID_($_[0]->windowid) }
sub tabobj { $_[0]->winobj->tabs->objectAtIndex_($_[0]->tabid) }
sub set_bg_color {
my ($obj, $bg_color) = @_;
$obj->tabobj->setBackgroundColor_($obj->make_NSColor($bg_color));
}
sub set_fg_color {
my ($obj, $fg_color) = @_;
$obj->tabobj->setNormalTextColor_($obj->make_NSColor($fg_color));
}
sub store_bg_color {
my ($obj, $bg) = @_;
*$obj->{'stored_bg_color'} = $obj->tabobj->backgroundColor();
}
sub store_fg_color {
my ($obj, $fg) = @_;
*$obj->{'stored_fg_color'} = $obj->tabobj->normalTextColor();
}
sub fetch_bg_color {
my ($obj) = @_;
return *$obj->{'stored_bg_color'} || '';
}
sub fetch_fg_color {
my ($obj) = @_;
return *$obj->{'stored_fg_color'} || '';
}
sub set_settings_set {
my ($obj,$want) = @_;
my $sets = $terminal->settingsSets;
for (my $i=0; $i<$sets->count; $i++) {
my $set = $sets->objectAtIndex_($i);
if ($set->name->UTF8String eq $want) {
$obj->tabobj->setCurrentSettings_($set);
return 1;
}
}
return;
}
sub screen_bounds {
my ($obj) = @_;
my ($x,$y,$w,$h);
if ($cur_bounds) {
return $cur_bounds;
} elsif ($config->screen_bounds) {
($x,$y,$w,$h) = @{$config->screen_bounds};
} else {
my $scr = $config->screen;
($x,$y,$w,$h) = @{physical_screen_bounds($scr)};
}
$max_bounds = [ $x, $y, $w, $h ];
return $cur_bounds = [ $x, $y, $w, $h ];
}
sub physical_screen_bounds {
my ($scr) = @_;
$scr ||= 1;
$scr =~ /^(\d+)(?:-(\d+))?$/ || die "Screen must be a number (e.g. 1) or a range (e.g. 1-2)";
my ($s1, $s2) = ($1,$2);
my $displays = NSScreen->screens()->count;
die "No such screen [$s1], screen must be $displays or less"
if $s1 > $displays;
my $frame1 = NSScreen->screens->objectAtIndex_($s1-1)->visibleFrame;
my $scr1 = [ObjCStruct::NSRect->unpack($frame1)];
if (defined $s2) {
if (NSScreen->screensHaveSeparateSpaces) {
warn "screen ranges are only supported when they all use the same space";
return $scr1;
} else {
# If it's a screen range - try to find a rectangle that
# fits neatly across the screens
die "No such screen [$s2], screen must be $displays or less"
if $s2 > $displays;
my $frame2 = NSScreen->screens->objectAtIndex_($s2-1)->visibleFrame;
my $scr2 = [ObjCStruct::NSRect->unpack($frame2)];
my $out = [];
if ($scr2->[0] >= ($scr1->[0] + $scr1->[2])) {
# Left of scr2, is to right of right of scr1
$out->[0] = $scr1->[0];
$out->[2] = ($scr2->[0] + $scr2->[2]) - $scr1->[0];
} elsif ($scr1->[0] >= ($scr2->[0] + $scr2->[2])) {
# Left of scr1, is to right of right of scr2
$out->[0] = $scr2->[0];
$out->[2] = ($scr1->[0] + $scr1->[2]) - $scr2->[0];
} else {
$out->[0] = max($scr1->[0], $scr2->[0]);
$out->[2] = min($scr1->[2], $scr2->[2]);
}
if ($scr2->[1] >= ($scr1->[1] + $scr1->[3])) {
# Bottom of scr2, is above top of scr1
$out->[1] = $scr1->[1];
if ($scr2->[1] > ($scr1->[1] + $scr1->[3])) {
warn "window can't span a screen with visibility gaps";
$out->[3] = $scr1->[3];
} else {
$out->[3] = ($scr2->[1] + $scr2->[3]) - $scr1->[1];
}
} elsif ($scr1->[1] >= ($scr2->[1] + $scr2->[3])) {
# Bottom of scr1, is above top of scr2
$out->[1] = $scr2->[1];
if ($scr1->[1] > ($scr2->[1] + $scr2->[3])) {
warn "window can't span a screen with visibility gaps";
$out->[3] = $scr2->[3];
} else {
$out->[3] = ($scr1->[1] + $scr1->[3]) - $scr2->[1];
}
} else {
$out->[1] = max($scr1->[1], $scr2->[1]);
$out->[3] = min($scr1->[3], $scr2->[3]);
}
return $out;
}
} else {
return $scr1;
}
}
sub reset_bounds {
$cur_bounds = [ @$max_bounds ];
}
sub max_physical_bounds {
$cur_bounds = physical_screen_bounds($config->screen);
}
sub bounds {
my ($obj) = @_;
my ($x, $y) = ObjCStruct::NSPoint->unpack($obj->winobj->origin);
my ($w, $h) = ObjCStruct::NSSize->unpack($obj->winobj->size);
return [ $x, $y, $w, $h ];
}
sub move {
my ($obj, $dx, $dy) = @_;
eval {
my ($x, $y) = ObjCStruct::NSPoint->unpack($obj->winobj->origin);
$x += 5 * $dx;
$y -= 5 * $dy;
$obj->winobj->setOrigin_(ObjCStruct::NSPoint->new($x,$y));
};
}
sub grow {
my ($obj, $dw, $dh) = @_;
eval {
my ($w, $h) = ObjCStruct::NSSize->unpack($obj->winobj->size);
$w += 5 * $dw;
$h -= 5 * $dh;
$obj->winobj->setSize_(ObjCStruct::NSSize->new($w,$h));
};
}
sub close_window {
my ($obj) = @_;
eval {
$obj->winobj->closeSaving_savingIn_(OSType 'no ',undef);
};
}
sub hide {
my ($obj) = @_;
eval { $obj->winobj->setVisible_(0) };
}
sub minimise {
my ($obj) = @_;
eval { $obj->winobj->setMiniaturized_(1) };
}
sub run_ruby {
my ($obj, $code, @args) = @_;
open(my $ruby, '|-', '/usr/bin/ruby', '-', @args);
print $ruby $code;
close($ruby);
return $? >> 8;
}
sub set_space {
my ($obj, $space) = @_;
my $I = (length pack('L!',0) == 4 ) ? 'I' : 'L';
$obj->run_ruby("
require 'dl'
dl = DL::dlopen('/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices')
con = dl.sym('_CGSDefaultConnection', '${I}').call()
dl.sym('CGSMoveWorkspaceWindowList', '${I}${I}A${I}${I}').call(con[0], [Integer(ARGV[0])], 1, Integer(ARGV[1]))
", $obj->windowid, $space);
}
sub space {
my ($obj) = @_;
my $I = (length pack('L!',0) == 4 ) ? 'I' : 'L';
my $i = lc $I;
$obj->run_ruby("
require 'dl'
dl = DL::dlopen('/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices')
con = dl.sym('_CGSDefaultConnection', '${I}').call()
r,rs = dl.sym('CGSGetWindowWorkspace', '${I}${I}${I}${i}').call(con[0], Integer(ARGV[0]), 0)
exit rs[2]
", $obj->windowid);
}
# Cheeesy test to block until no modifier keys are pressed
sub wait_for_no_mod_keys {
1 while NSEvent->modifierFlags != 0
}
sub split {
my ($obj) = @_;
$obj->winobj->setFrontmost_(1);
wait_for_no_mod_keys();
$obj->winobj->setFrontmost_(1);
$sysevents->keystroke_using_('d', 'Kcmd');
$obj->winobj->setFrontmost_(1);
}
sub unsplit {
my ($obj) = @_;
$obj->winobj->setFrontmost_(1);
wait_for_no_mod_keys();
$obj->winobj->setFrontmost_(1);
$sysevents->keystroke_using_('D', 'Kcmd');
$obj->winobj->setFrontmost_(1);
}
sub font_shrink {
my ($obj) = @_;
$obj->winobj->setFrontmost_(1);
wait_for_no_mod_keys();
$obj->winobj->setFrontmost_(1);
$sysevents->keystroke_using_('-', 'Kcmd');
$obj->winobj->setFrontmost_(1);
}
# This is failing due to "shift" being pressed :-(
sub font_grow {
my ($obj) = @_;
$obj->winobj->setFrontmost_(1);
wait_for_no_mod_keys();
$obj->winobj->setFrontmost_(1);
$sysevents->keystroke_using_('+', 'Kcmd');
$obj->winobj->setFrontmost_(1);
}
sub clear_scrollback {
my ($obj) = @_;
$obj->winobj->setFrontmost_(1);
wait_for_no_mod_keys();
$obj->winobj->setFrontmost_(2);
$sysevents->keystroke_using_('k', 'Kcmd');
$obj->winobj->setFrontmost_(1);
}
sub terminate {
my ($obj) = @_;
$obj->set_windowid(undef);
$obj->set_tabid(undef);
$obj->SUPER::terminate();
}
#==============================================================================#
package CsshX::Window::Master;
use base qw(CsshX::Window);
sub format_master {
my ($obj) = @_;
my $fg = $obj->make_NSColor($config->color_master_foreground);
my $bg = $obj->make_NSColor($config->color_master_background);
my $mh = $config->master_height;
my ($x,$y,$w,$h) = @{$obj->screen_bounds};
eval {
$obj->winobj->setMiniaturized_(0);
$obj->winobj->setSize_(ObjCStruct::NSSize->new($w,$mh));
$obj->winobj->setOrigin_(ObjCStruct::NSPoint->new($x,$y));
$obj->tabobj->setBackgroundColor_($bg);
$obj->tabobj->setNormalTextColor_($fg);
$obj->winobj->setFrontmost_(1);
# Now check the height of the terminal window in case it's larger than
# expected, if so, move it off the bottom of the screen if possible
my ($real_mw, $real_mh) = ObjCStruct::NSSize->unpack($obj->winobj->size());
$obj->winobj->setOrigin_(
ObjCStruct::NSPoint->new($x, ($y-($real_mh-$mh)))
) if ($real_mh > $mh);
};
}
sub format_resize {
my ($obj) = @_;
my $bg_color = $config->color_setbounds_background;
my $fg_color = $config->color_setbounds_foreground;
$obj->set_bg_color($bg_color) if $bg_color;
$obj->set_fg_color($fg_color) if $fg_color;
}
sub size_as_bounds {
my ($obj) = @_;
my ($x,$y,$w,$h) = @{$obj->screen_bounds};
eval {
$obj->winobj->setMiniaturized_(0);
$obj->winobj->setSize_(ObjCStruct::NSSize->new($w,$h));
$obj->winobj->setOrigin_(ObjCStruct::NSPoint->new($x,$y));
$obj->winobj->setFrontmost_(1);
};
}
sub bounds_as_size {
my ($obj) = @_;
my $win_bounds = $obj->bounds;
$cur_bounds = $win_bounds;
}
sub move_slaves_to_master_space {
my ($obj) = @_;
$obj->run_ruby("
require 'fiddle'
require 'fiddle/import'
module LibCGS
extend Fiddle::Importer
dlload '/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices'
extern 'int _CGSDefaultConnection(int)'
extern 'int CGSMoveWorkspaceWindowList(int, int*, int, int)'
end
ARGV.map! {|wid| Integer(wid)}
con = LibCGS._CGSDefaultConnection(0)
ptr = Fiddle::Pointer[ARGV.pack('i*')]
LibCGS.CGSMoveWorkspaceWindowList(con, ptr, ARGV.length, 1000)
", map {$_->windowid} $obj, CsshX::Master::Socket::Slave->slaves);
}
#==============================================================================#
package CsshX::Window::Slave;
use base qw(CsshX::Window);
use POSIX qw(ceil);
my $slaveids_by_location = [];
my $current_selection = [0,0];
sub location { @{*{$_[0]}->{location}}; }
sub set_location {
my ($obj, $x, $y) = @_;
*$obj->{location} = [$x,$y];
}
sub disabled { *{$_[0]}->{disabled}; }
sub set_disabled {
my ($obj, $value) = @_;
return if ((*$obj->{disabled} && $value) || ((!*$obj->{disabled}) && (!$value)));
*$obj->{disabled} = $value;
$obj->format_color('dis');
}
sub selected { *{$_[0]}->{selected}; }
sub set_selected {
my ($obj, $value) = @_;
return if ((*$obj->{selected} && $value) || ((!*$obj->{selected}) && (!$value)));
*$obj->{selected} = $value;
$obj->format_color('sel');
}
sub format_color {
my ($obj, $type) = @_;
my $sel = *$obj->{selected};
my $dis = *$obj->{disabled};
if ($sel && $config->color_selected_background) {
unless ($dis && $config->color_disabled_background) {
$obj->store_bg_color if $type eq 'sel';
}
$obj->set_bg_color($config->color_selected_background);
} elsif ($dis && $config->color_disabled_background) {
$obj->store_bg_color if $type eq 'dis';
$obj->set_bg_color($config->color_disabled_background);
} elsif (my $bg = $obj->fetch_bg_color) {
$obj->set_bg_color($bg);
}
if ($dis && $config->color_disabled_foreground) {
unless ($sel && $config->color_selected_foreground) {
$obj->store_fg_color if $type eq 'dis';
}
$obj->set_fg_color($config->color_disabled_foreground);
} elsif ($sel && $config->color_selected_foreground) {
$obj->store_fg_color if $type eq 'sel';
$obj->set_fg_color($config->color_selected_foreground);
} elsif (my $fg = $obj->fetch_fg_color) {
$obj->set_fg_color($fg);
}
}
sub get_by_location {
my ($pack,$x,$y) = @_;
if ($slaveids_by_location) {