Move to Apache License
[amazing.git] / lib / amazing / x11 / display_name.rb
bloba84d6660bbbcfaa382392c51a7737aa6b42e1cdf
1 # Copyright 2008 Dag Odenhall <dag.odenhall@gmail.com>
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 #    http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 module Amazing
16   module X11
18     # Raised by DisplayName#new if called with empty argument, or without
19     # argument and ENV["DISPLAY"] is empty.
20     class EmptyDisplayName < ArgumentError
21     end
23     # Raised by DisplayName#new if format of argument or ENV["DISPLAY"] is
24     # invalid.
25     class InvalidDisplayName < ArgumentError
26     end
28     # Parse an X11 display name
29     #
30     #   display = DisplayName.new("hostname:displaynumber.screennumber")
31     #   display.hostname #=> "hostname"
32     #   display.display  #=> "displaynumber"
33     #   display.screen   #=> "screennumber"
34     #
35     # Without arguments, reads ENV["DISPLAY"]. With empty argument or
36     # DISPLAY environment, raises EmptyDisplayName. With invalid display name
37     # format, raises InvalidDisplayName. 
38     class DisplayName
39       attr_reader :hostname, :display, :screen
41       def initialize(display_name=ENV["DISPLAY"])
42         raise EmptyDisplayName, "No display name supplied" if ["", nil].include? display_name
43         @hostname, @display, @screen = display_name.scan(/^(.*):(\d+)(?:\.(\d+))?$/)[0]
44         raise InvalidDisplayName, "Invalid display name" if @display.nil?
45         @hostname = "localhost" if @hostname.empty?
46         @screen = "0" unless @screen
47       end
48     end
49   end
50 end