Start screenshot server
false
false
true
macros_menu.examples>end("Examples").end
ruby
# @title Using the Qt binding: convert KLayout into a HTTP server
#
# This example employs the Qt binding of KLayout.
# It converts KLayout into a HTTP server running on port 8081 which delivers a HTML page with a snapshot of the current view.
# To run it choose "Run current script" (Shift+F5) in the macro IDE. The server will keep running
# when the IDE is closed.
#
module Examples
require 'tempfile'
# Implements a TCP server listening on port 8081
# This server will accept HTTP requests and deliver a HTML page containing an image
# with the current snapshot.
class MyServer < RBA::QTcpServer
# Initialize the server and put into listen mode (port is 8081)
def initialize(parent = nil)
super
ha = RBA::QHostAddress.new("0.0.0.0")
listen(ha, 8081)
self.newConnection do
self.connection
end
end
# Signals an incoming connection
def connection
begin
connection = nextPendingConnection
url = nil
while connection.isOpen
if connection.canReadLine
line = connection.readLine.to_s
if line.chomp == ""
break
elsif line =~ /GET\s+(.*)\s+HTTP/
url = RBA::QUrl.new($1)
end
else
connection.waitForReadyRead(100)
end
end
if url && url.path == "/screenshot.png"
# Delivers the image
view = RBA::Application.instance.main_window.current_view
if view
tmp = Tempfile.new("klayout-screenshot")
image = view.save_image(tmp.path, 400, 400)
tmpin = RBA::QFile.new(tmp.path)
tmpin.open(RBA::QFile::ReadOnly)
connection.write(tmpin.readAll)
tmpin.close
tmp.close
end
elsif url && url.path == "/screenshot.html"
# Delivers the HTML page
connection.write(<<"END")
HTTP/1.1 200 OK
Server: KLayout
Content-Type: text/html
Content-Disposition: inline
Connection: Closed
<html><body><image src="screenshot.png"/></body></html>
END
else
connection.write("Invalid URL")
end
connection.disconnectFromHost()
rescue
puts "ERROR #{$!}"
end
end
end
# Kill any running server
@server && @server._destroy
# Start the screenshot server
@server = MyServer.new
end