Kaydet (Commit) 05885a35 authored tarafından Fatih Aşıcı's avatar Fatih Aşıcı

move

üst 3eaadc08
This diff is collapsed.
recursive-include zorg/ddc *.h
include data/*DB
include COPYING README TODO
What is zorg?
-------------
zorg consists of python scripts and modules which
automate the configuration of Xorg.
Requirements
------------
* libx86
Installing & Running
--------------------
1. Apply the patch comar/model.xml.patch in /etc/comar
2. Register Çomar script:
hav register Xorg.Display zorg comar/xorg.display.py
3. Install:
./setup.py install --install-lib=/usr/lib/pardus
4. Run: zorg-cli
zorg TODO List
==============
Legend:
- Todo
? Not determined if/how we have to do
/ In progress
+ Accomplished
Çomar Methods:
- configuration setup on boot
- check config files
- check hardware changes
- read kernel options (xorg=...)
- force auto-probe if requested (e.g. with an option from GUI)
? compatibility check between kernel and xorg driver versions (e.g. nvidia-kernel and nvidia-glx issue)
- method access attributes
- i18n support
- DPI setup
- INF file installation
- method to test server
? fall back to safeConfigure if something goes wrong while auto-probing
- improve debug stuff (maybe a log file)
Modules:
- setup opengl headers
- try to get preferred resolution and use it by default
- parser to get monitor vendor/model list
- expand vendor name from EISA ID (e.g. SAM0101 -> Samsung)
Command Line Tool:
- test option
? DPI selection
? Xorg log file verbosity selection
? bug report option/tool
This diff is collapsed.
This diff is collapsed.
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# inf2mondb.py: convert .inf files for monitors to MonitorDB
#
# Matt Wilson <msw@redhat.com>
#
# Copyright 2002 Red Hat, Inc.
#
# Some fixes by Onur Küçük <onur@pardus.org.tr>
#
# This software may be freely redistributed under the terms of the GNU
# library public license.
import sys
import string
import re
def usage():
print "Usage: inf2mondb.py filename.inf"
sys.exit(1)
if len(sys.argv) < 2:
usage()
try:
f = open(sys.argv[1], 'r')
except IOError, (errno, str):
print "Unable to open %s: %s" % (sys.argv[1], str)
sys.exit(1)
lines = f.readlines()
f.close()
# the current section
section = None
# monitors - a dictionary keyed off manufacturers
monitors = {}
# a dictionary of manufacturers we're looking at
manufacturers = {}
# registry sections mapped back to the install sections
regsections = {}
# install sections that map back to monitor definitions
instsections = {}
# a big fat dictionary of strings to use later on.
strings = {}
class Monitor:
def __repr__(self):
return "%s; %s; %s; %s; %s" % (self.man,
self.descr,
self.edid,
self.hsync,
self.vsync)
def __init__(self, man, id, edid):
self.descr = ""
self.man = man
self.hsync = ""
self.vsync = ""
self.id = id
self.edid = edid
sectRe = re.compile(r'\[*\]')
sectSplit = re.compile(r'[\[\]]')
infoSplit = re.compile(r'[%=\\;]')
# This RE is for EISA info lines
# %D5259A%=D5259A, Monitor\HWP0487
monitor1Re = re.compile(r'%*.%.*=.*,.*Monitor\\')
# This one is for legacy entries
# %3020% =PB3020, MonID_PB3020
monitor2Re = re.compile(r'%*.%.*=.*,.*MonID_')
# sync values that might be in the strings section
sync_keys = {}
for line in lines:
tmp = string.strip(line)
if tmp and tmp[0] == ';':
continue
if sectRe.search (line, 1):
section = string.lower(sectSplit.split (line)[1])
continue
if section == "manufacturer":
tmp = infoSplit.split (line)
if len(tmp) > 1:
manufacturer = string.lower(tmp[1])
if manufacturers.has_key (tmp[1]):
raise RuntimeError, "Duplicate manufacturer entries"
else:
manufacturers[string.lower(string.strip(tmp[3].split(",")[0]))] = string.lower(string.strip(tmp[1]))
# if we're in a manufacturer section, we need to jot down
# the devices
elif manufacturers.has_key(section):
# Find monitor inf IDs and EISA ids:
monre = None
# EISA entries
# %D5259A%=D5259A, Monitor\HWP0487
if monitor1Re.search(line, 1):
monre = monitor1Re
# older non EISA entries
# %3020% =PB3020, MonID_PB3020
elif monitor2Re.search(line, 1):
monre = monitor2Re
if monre:
end = monre.search(line, 1).end()
id = string.strip(string.split(line, '%')[1])
if monre == monitor1Re:
# all EDID ID strings are 7 chars
edid = string.strip(line[end:])[0:7]
else:
edid = "0"
# we need to get the install section for this device
rhs = string.strip(string.split (line, '=')[1])
install = string.lower(string.strip(string.split (rhs, ',')[0]))
if instsections.has_key (install):
instsections[install].append ((section, id))
else:
instsections[install] = [ (section, id) ]
if not monitors.has_key (section):
monitors[section] = {}
monitors[section][id] = Monitor(section, id, edid)
elif section == "strings":
tmp = string.strip(tmp)
if not tmp:
continue
tmp = string.split (line, '=')
if len (tmp) < 2:
continue
key = string.lower(string.strip(tmp[0]))
tmp = string.split(string.strip(tmp[1]), '"')
if len (tmp) > 1:
value = tmp[1]
else:
value = tmp[0]
strings[key] = string.strip(value)
# Deal with sync lines in the strings section
if sync_keys.has_key(key):
sync = string.split(value, ",")
for (man, mon) in sync_keys[key]:
monitors[man][mon].hsync = string.strip(sync[0])
monitors[man][mon].vsync = string.strip(sync[1])
# these are the sections that tell us which AddReg to use
# AddReg=PBCOM14L.AddReg, 1024, DPMS
elif instsections.has_key(section):
if string.find (line, "AddReg=") >= 0:
rhs = string.split (line, '=')[1]
# PBCOM14L.AddReg, 1024, DPMS
registry = string.lower(string.strip(string.split(rhs, ',')[0]))
# add this monitor to the list of monitors that will
# use this registry entry
if regsections.has_key(registry):
regsections[registry].append (section)
else:
regsections[registry] = [ section ]
# these are the actual AddReg entries. Look up in our table
# to find which
elif regsections.has_key(section):
if string.find(line, 'HKR') >= 0:
ids = regsections[section]
# make a list of all the monitors pointing to
# this registry section via install sections
mons = []
for id in ids:
mons = mons + instsections[id]
if string.find(line, 'HKR,"MODES') >= 0:
modes = string.split(line, '"')
sync = string.split(modes[3], ',')
for (man, mon) in mons:
monitors[man][mon].hsync = string.strip(sync[0])
monitors[man][mon].vsync = string.strip(sync[1])
else:
# Sync lines must be somewhere else, maybe in the strings section
keyval = None
try:
keyval = string.split(line,",")[4]
except IndexError:
pass
if keyval and string.find(keyval, "KeyValue") >= 0:
keyval = string.replace(string.strip(keyval), "%", "").lower()
sync_keys[keyval] = mons
for man in manufacturers.keys():
for monitor in monitors[man].values():
# OK, I know it's hacked up to look up these strings way down
# here, but .inf format is CRAP.
try:
monitor.descr = strings[string.lower(monitor.id)]
except KeyError:
monitor.descr = monitor.id
try:
monitor.man = strings[string.lower(manufacturers[man])]
except:
monitor.man = manufacturers[man]
print monitor
#!/usr/bin/python
#-*- coding: utf-8 -*-
from distutils.core import setup, Extension
import zorg
setup(name="zorg",
version=zorg.versionString(),
description="Python Modules for zorg",
license="GNU GPL2",
url="http://www.pardus.org.tr/",
packages = ["zorg"],
ext_modules = [Extension("zorg.ddc",
sources=["zorg/ddc/ddc.c",
"zorg/ddc/vbe.c",
"zorg/ddc/vesamode.c"],
libraries=["x86"])],
scripts = ["zorg-cli", "inf2mondb"],
data_files = [("/usr/lib/X11", ["data/DriversDB", "data/MonitorsDB"])]
)
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2008 TUBITAK/UEKAE
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
import optparse
import sys
import dbus
import zorg
zorg_info = " Xorg AutoConfiguration tool"
class ComarLink:
def __init__(self):
self.bus = None
self.iface = None
def __getattr__(self, method):
if not self.iface:
self._connect()
return getattr(self.iface, method)
def _connect(self):
self.bus = dbus.SystemBus()
object = self.bus.get_object("tr.org.pardus.comar", "/package/zorg", introspect=False)
self.iface = dbus.Interface(object, "tr.org.pardus.comar.Xorg.Display")
link = ComarLink()
def safe():
if link.safeConfig():
print "Initialized a safe configuration using VESA driver."
else:
print "Failed to create a safe configuration with VESA driver."
def probe(opts):
if link.initialConfig():
print "Created an initial configuration for your video device."
else:
print "An error occured while creating an initial configuration."
def setMode(opts):
pass
def setDriver(driver):
pass
if __name__ == "__main__":
parser = optparse.OptionParser(description = "%s version %s"
% (zorg_info, zorg.versionString()))
parser.add_option("-s", "--safe", action="store_true",
dest="safe", default=False,
help="setup VESA 800x600 config without probing hardware")
parser.add_option("-p", "--probe", action="store_true",
dest="probe", default=False,
help="force probing all devices, even if xorg.conf exists")
parser.add_option("-m", "--mode", action="store", type="string",
dest="mode", default=None,
help="use MODE given in form <width>x<height>[-<depth>] if supported")
parser.add_option("-d", "--driver", action="store", type="string",
dest="driver", default=None,
help="set video card driver to DRIVER")
opts, args = parser.parse_args()
if opts.safe:
safe()
elif opts.probe:
probe(opts)
elif opts.mode or opts.driver:
if opts.mode:
setMode(opts)
if opts.driver:
setDriver(opts.driver)
else:
parser.print_help()
#-*- coding: utf-8 -*-
#
# Copyright (C) 2007, TUBITAK/UEKAE
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
__version__ = "0.92"
__all__ = ["config",
"ddc",
"modeline",
"parser",
"probe",
"utils"]
def versionString():
return __version__
# -*- coding: utf-8 -*-
import os
import piksemel
from zorg.parser import *
from zorg.probe import VideoDevice, Monitor
from zorg.utils import atoi
xorgConf = "/etc/X11/xorg.conf"
zorgConfigDir = "/var/lib/zorg"
zorgConfig = "config.xml"
def saveXorgConfig(card):
parser = XorgParser()
secModule = XorgSection("Module")
secdri = XorgSection("dri")
secFiles = XorgSection("Files")
secFlags = XorgSection("ServerFlags")
secDevice = XorgSection("Device")
secScr = XorgSection("Screen")
secLay = XorgSection("ServerLayout")
parser.sections = [
secModule,
secdri,
secFiles,
secFlags,
secLay,
secScr,
secDevice
]
extmod = XorgSection("extmod")
extmod.options = {"omit xfree86-dga" : unquoted()}
secModule.sections = [extmod]
secdri.set("Mode", unquoted("0666"))
secFiles.set("RgbPath", "/usr/lib/X11/rgb")
fontPaths = (
"/usr/share/fonts/misc/",
"/usr/share/fonts/dejavu/",
"/usr/share/fonts/TTF/",
"/usr/share/fonts/freefont/",
"/usr/share/fonts/TrueType/",
"/usr/share/fonts/corefonts",
"/usr/share/fonts/Speedo/",
"/usr/share/fonts/Type1/",
"/usr/share/fonts/100dpi/",
"/usr/share/fonts/75dpi/",
"/usr/share/fonts/encodings/",
)
for fontPath in fontPaths:
secFiles.add("FontPath", fontPath)
secFlags.options = {
"AllowEmptyInput" : "true",
"AllowMouseOpenFail" : "true",
"BlankTime" : "0",
"StandbyTime" : "0",
"SuspendTime" : "0",
"OffTime" : "0"
}
info = card.getDict()
#secDevice.set("Screen", screenNumber)
secDevice.set("Identifier", "VideoCard")
secDevice.set("Driver", card.driver)
#secDevice.set("VendorName", dev.vendorName)
#secDevice.set("BoardName", dev.boardName)
secDevice.set("BusId", info["bus-id"])
secDevice.options.update(card.driver_options)
flags = card.probe_result["flags"].split(",")
for output in card.active_outputs:
identifier = "Monitor[%s]" % output
monSec = XorgSection("Monitor")
parser.sections.append(monSec)
monSec.set("Identifier", identifier)
if card.monitors.has_key(output):
monSec.set("HorizSync", unquoted("%s - %s" % card.monitors[output].hsync))
monSec.set("VertRefresh", unquoted("%s - %s" % card.monitors[output].vref))
if "randr12" in flags:
secDevice.options["Monitor-%s" % output] = identifier
if card.modes.has_key(output):
monSec.options["PreferredMode"] = card.modes[output]
monSec.options["Enabled"] = "true"
secScr.set("Identifier", "Screen")
secScr.set("Device", "VideoCard")
secScr.set("Monitor", "Monitor[%s]" % card.active_outputs[0])
secScr.set("DefaultDepth", atoi(card.depth))
subsec = XorgSection("Display")
subsec.set("Depth", atoi(card.depth))
if "no-modes-line" not in flags:
output = card.active_outputs[0]
if card.modes.has_key(output):
subsec.set("Modes", card.modes[output], "800x600", "640x480")
secScr.sections = [subsec]
secLay.set("Identifier", "Layout")
secLay.set("Screen", "Screen")
f = open(xorgConf, "w")
f.write(parser.toString())
f.close()
def addTag(p, name, data):
t = p.insertTag(name)
t.insertData(data)
def getDeviceInfo(busId):
configFile = os.path.join(zorgConfigDir, zorgConfig)
if not os.path.exists(configFile):
return
doc = piksemel.parse(configFile)
cardTag = None
for tag in doc.tags("Card"):
if tag.getAttribute("busId") == busId:
cardTag = tag
break
if not cardTag:
return
device = VideoDevice(busId=busId)
driversTag = cardTag.getTag("Drivers")
drivers = []
for tag in driversTag.tags("Driver"):
drvname = tag.firstChild().data()
drvpackage = tag.getAttribute("package")
if drvpackage != "xorg-video":
drvname += ":%s" % drvpackage
drivers.append(drvname)
probeResultTag = cardTag.getTag("ProbeResult")
probeResult = {}
for tag in probeResultTag.tags("Value"):
key = tag.getAttribute("key")
child = tag.firstChild()
if child:
value = child.data()
else:
value = ""
probeResult[key] = value
monitorsTag = cardTag.getTag("Monitors")
for tag in monitorsTag.tags("Monitor"):
mon = Monitor()
mon.eisaid = tag.getAttribute("id")
output = tag.getAttribute("output")
device.monitors[output] = mon
hsync = tag.getTag("HorizSync")
min = hsync.getAttribute("min")
max = hsync.getAttribute("max")
mon.hsync = (min, max)
vref = tag.getTag("VertRefresh")
min = vref.getAttribute("min")
max = vref.getAttribute("max")
mon.vref = (min, max)
activeConfigTag = cardTag.getTag("ActiveConfig")
driverTag = activeConfigTag.getTag("Driver")
device.driver = driverTag.firstChild().data()
device.package = driverTag.getAttribute("package")
device.depth = activeConfigTag.getTagData("Depth")
activeOutputs = []
modes = {}
for tag in activeConfigTag.tags("Output"):
name = tag.firstChild().data()
mode = tag.getAttribute("mode")
activeOutputs.append(name)
if mode:
modes[name] = mode
device.desktop_setup = activeConfigTag.getTagData("DesktopSetup")
device.driverlist = drivers
device.probe_result = probeResult
device.active_outputs = activeOutputs
device.modes = modes
return device
def saveDeviceInfo(card):
if not os.path.exists(zorgConfigDir):
os.mkdir(zorgConfigDir, 0755)
configFile = os.path.join(zorgConfigDir, zorgConfig)
try:
doc = piksemel.parse(configFile)
except OSError:
doc = piksemel.newDocument("ZORG")
info = card.getDict()
for tag in doc.tags("Card"):
if tag.getAttribute("busId") == info["bus-id"]:
tag.hide()
break
cardTag = doc.insertTag("Card")
cardTag.setAttribute("busId", info["bus-id"])
#addTag(cardTag, "VendorId", card.vendor_id)
#addTag(cardTag, "ProductId", card.product_id)
drivers = cardTag.insertTag("Drivers")
for driver in card.driverlist:
if ":" in driver:
drv, pkg = driver.split(":", 1)
else:
drv = driver
pkg = "xorg-video"
d = drivers.insertTag("Driver")
d.setAttribute("package", pkg)
d.insertData(drv)
probeResult = cardTag.insertTag("ProbeResult")
for key, value in card.probe_result.items():
t = probeResult.insertTag("Value")
t.setAttribute("key", key)
if value:
t.insertData(value)
monitors = cardTag.insertTag("Monitors")
for output, monitor in card.monitors.items():
monitorTag = monitors.insertTag("Monitor")
monitorTag.setAttribute("id", monitor.eisaid)
monitorTag.setAttribute("output", output)
min, max = monitor.hsync
hor = monitorTag.insertTag("HorizSync")
hor.setAttribute("min", min)
hor.setAttribute("max", max)
min, max = monitor.vref
ver = monitorTag.insertTag("VertRefresh")
ver.setAttribute("min", min)
ver.setAttribute("max", max)
config = cardTag.insertTag("ActiveConfig")
driver = config.insertTag("Driver")
driver.setAttribute("package", card.package)
driver.insertData(card.driver)
addTag(config, "Depth", card.depth)
outName = card.active_outputs[0]
outMode = card.modes.get(outName)
output = config.insertTag("Output")
if outMode:
output.setAttribute("mode", outMode)
output.insertData(outName)
addTag(config, "DesktopSetup", card.desktop_setup)
if card.desktop_setup != "single":
outName = card.active_outputs[1]
outMode = card.modes.get(outName)
output = config.insertTag("SecondOutput")
if outMode:
output.setAttribute("mode", outMode)
output.insertData(outName)
f = file(configFile, "w")
f.write(doc.toPrettyString())
f.close()
This diff is collapsed.
This diff is collapsed.
#ifndef vbe_h
#define vbe_h
#ident "$Id: vbe.h,v 1.1 1999/11/15 13:02:13 prigaux Exp $"
#include <sys/types.h>
/* Record returned by int 0x10, function 0x4f, subfunction 0x00. */
struct vbe_info {
unsigned char signature[4];
unsigned char version[2];
union {
struct {
u_int16_t ofs;
u_int16_t seg;
} addr;
const char *string;
} oem_name;
u_int32_t capabilities;
union {
struct {
u_int16_t ofs;
u_int16_t seg;
} addr;
u_int16_t *list;
} mode_list;
u_int16_t memory_size;
/* VESA 3.0+ */
u_int16_t vbe_revision;
union {
struct {
u_int16_t ofs;
u_int16_t seg;
} addr;
const char *string;
} vendor_name;
union {
struct {
u_int16_t ofs;
u_int16_t seg;
} addr;
const char *string;
} product_name;
union {
struct {
u_int16_t ofs;
u_int16_t seg;
} addr;
const char *string;
} product_revision;
char reserved1[222];
char reserved2[256];
} __attribute__ ((packed));
/* Stuff returned by int 0x10, function 0x4f, subfunction 0x01. */
struct vbe_mode_info {
/* required for all VESA versions */
struct {
/* VBE 1.0+ */
u_int16_t supported: 1;
u_int16_t optional_info_available: 1;
u_int16_t bios_output_supported: 1;
u_int16_t color: 1;
u_int16_t graphics: 1;
/* VBE 2.0+ */
u_int16_t not_vga_compatible: 1;
u_int16_t not_bank_switched: 1;
u_int16_t lfb: 1;
/* VBE 1.0+ */
u_int16_t unknown: 1;
u_int16_t must_enable_directaccess_in_10: 1;
} mode_attributes;
struct {
unsigned char exists: 1;
unsigned char readable: 1;
unsigned char writeable: 1;
unsigned char reserved: 5;
} windowa_attributes, windowb_attributes;
u_int16_t window_granularity;
u_int16_t window_size;
u_int16_t windowa_start_segment, windowb_start_segment;
u_int16_t window_positioning_seg, window_positioning_ofs;
u_int16_t bytes_per_scanline;
/* optional for VESA 1.0/1.1, required for OEM modes */
u_int16_t w, h;
unsigned char cell_width, cell_height;
unsigned char memory_planes;
unsigned char bpp;
unsigned char banks;
enum {
memory_model_text = 0,
memory_model_cga = 1,
memory_model_hgc = 2,
memory_model_ega16 = 3,
memory_model_packed_pixel = 4,
memory_model_sequ256 = 5,
memory_model_direct_color = 6,
memory_model_yuv = 7,
} memory_model: 8;
unsigned char bank_size;
unsigned char image_pages;
unsigned char reserved1;
/* required for VESA 1.2+ */
unsigned char red_mask, red_field;
unsigned char green_mask, green_field;
unsigned char blue_mask, blue_field;
unsigned char reserved_mask, reserved_field;
unsigned char direct_color_mode_info;
/* VESA 2.0+ */
u_int32_t linear_buffer_address;
u_int32_t offscreen_memory_address;
u_int16_t offscreen_memory_size;
unsigned char reserved2[206];
} __attribute__ ((packed));
/* Modeline information used by XFree86. */
struct vbe_modeline {
u_int16_t width, height;
unsigned char interlaced;
float refresh;
char *modeline;
float hfreq, vfreq, pixel_clock;
};
/* Aspect ratios used in EDID info. */
enum vbe_edid_aspect {
aspect_unknown = 0,
aspect_75,
aspect_8,
aspect_5625,
};
/* Detailed timing information used in EDID v1.x */
struct vbe_edid_detailed_timing {
u_int16_t pixel_clock;
#define VBE_EDID_DETAILED_TIMING_PIXEL_CLOCK(_x) \
((_x).pixel_clock * 10000)
unsigned char horizontal_active;
unsigned char horizontal_blanking;
unsigned char horizontal_blanking_hi: 4;
unsigned char horizontal_active_hi: 4;
#define VBE_EDID_DETAILED_TIMING_HORIZONTAL_ACTIVE(_x) \
(((_x).horizontal_active_hi << 8) + (_x).horizontal_active)
#define VBE_EDID_DETAILED_TIMING_HORIZONTAL_BLANKING(_x) \
(((_x).horizontal_blanking_hi << 8) + (_x).horizontal_blanking)
unsigned char vertical_active;
unsigned char vertical_blanking;
unsigned char vertical_blanking_hi: 4;
unsigned char vertical_active_hi: 4;
#define VBE_EDID_DETAILED_TIMING_VERTICAL_ACTIVE(_x) \
(((_x).vertical_active_hi << 8) + (_x).vertical_active)
#define VBE_EDID_DETAILED_TIMING_VERTICAL_BLANKING(_x) \
(((_x).vertical_blanking_hi << 8) + (_x).vertical_blanking)
unsigned char hsync_offset;
unsigned char hsync_pulse_width;
unsigned char vsync_pulse_width: 4;
unsigned char vsync_offset: 4;
unsigned char vsync_pulse_width_hi: 2;
unsigned char vsync_offset_hi: 2;
unsigned char hsync_pulse_width_hi: 2;
unsigned char hsync_offset_hi: 2;
#define VBE_EDID_DETAILED_TIMING_HSYNC_OFFSET(_x) \
(((_x).hsync_offset_hi << 8) + (_x).hsync_offset)
#define VBE_EDID_DETAILED_TIMING_HSYNC_PULSE_WIDTH(_x) \
(((_x).hsync_pulse_width_hi << 8) + (_x).hsync_pulse_width)
#define VBE_EDID_DETAILED_TIMING_VSYNC_OFFSET(_x) \
(((_x).vsync_offset_hi << 4) + (_x).vsync_offset)
#define VBE_EDID_DETAILED_TIMING_VSYNC_PULSE_WIDTH(_x) \
(((_x).vsync_pulse_width_hi << 4) + (_x).vsync_pulse_width)
unsigned char himage_size;
unsigned char vimage_size;
unsigned char vimage_size_hi: 4;
unsigned char himage_size_hi: 4;
#define VBE_EDID_DETAILED_TIMING_HIMAGE_SIZE(_x) \
(((_x).himage_size_hi << 8) + (_x).himage_size)
#define VBE_EDID_DETAILED_TIMING_VIMAGE_SIZE(_x) \
(((_x).vimage_size_hi << 8) + (_x).vimage_size)
unsigned char hborder;
unsigned char vborder;
struct {
unsigned char stereo_mode: 1;
unsigned char vsync_positive: 1;
unsigned char hsync_positive: 1;
unsigned char separate_sync: 2;
unsigned char stereo: 2;
unsigned char interlaced: 1;
} flags __attribute__ ((packed));
} __attribute__ ((packed));
enum {
vbe_edid_monitor_descriptor_serial = 0xff,
vbe_edid_monitor_descriptor_ascii = 0xfe,
vbe_edid_monitor_descriptor_range = 0xfd,
vbe_edid_monitor_descriptor_name = 0xfc,
} vbe_edid_monitor_descriptor_types;
struct vbe_edid_monitor_descriptor {
u_int16_t zero_flag_1;
unsigned char zero_flag_2;
unsigned char type;
unsigned char zero_flag_3;
union {
char string[13];
struct {
unsigned char vertical_min;
unsigned char vertical_max;
unsigned char horizontal_min;
unsigned char horizontal_max;
unsigned char pixel_clock_max;
unsigned char gtf_data[8];
} range_data;
} data;
} __attribute__ ((packed));
struct vbe_edid1_info {
unsigned char header[8];
struct {
u_int16_t char3: 5;
u_int16_t char2: 5;
u_int16_t char1: 5;
u_int16_t zero: 1;
} manufacturer_name __attribute__ ((packed));
u_int16_t product_code;
u_int32_t serial_number;
unsigned char week;
unsigned char year;
unsigned char version;
unsigned char revision;
struct {
unsigned char serration_vsync: 1;
unsigned char sync_on_green: 1;
unsigned char composite_sync: 1;
unsigned char separate_sync: 1;
unsigned char blank_to_blank_setup: 1;
unsigned char video_level: 2;
unsigned char digital: 1;
} video_input_definition __attribute__ ((packed));
unsigned char max_size_horizontal;
unsigned char max_size_vertical;
unsigned char gamma;
struct {
unsigned char default_gtf_supported: 1;
unsigned char pereferred_timing_mode: 1;
unsigned char standard_color_space: 1;
unsigned char display_type: 2;
unsigned char active_off: 1;
unsigned char suspend: 1;
unsigned char standby: 1;
} feature_support __attribute__ ((packed));
unsigned char color_characteristics[10];
struct {
unsigned char timing_1280x1024_75: 1;
unsigned char timing_1024x768_75: 1;
unsigned char timing_1024x768_70: 1;
unsigned char timing_1024x768_60: 1;
unsigned char timing_1024x768_87i: 1;
unsigned char timing_832x624_75: 1;
unsigned char timing_800x600_75: 1;
unsigned char timing_800x600_72: 1;
unsigned char timing_800x600_60: 1;
unsigned char timing_800x600_56: 1;
unsigned char timing_640x480_75: 1;
unsigned char timing_640x480_72: 1;
unsigned char timing_640x480_67: 1;
unsigned char timing_640x480_60: 1;
unsigned char timing_720x400_88: 1;
unsigned char timing_720x400_70: 1;
} established_timings __attribute__ ((packed));
struct {
unsigned char timing_1152x870_75: 1;
unsigned char reserved: 7;
} manufacturer_timings __attribute__ ((packed));
struct {
u_int16_t xresolution: 8;
u_int16_t vfreq: 6;
u_int16_t aspect: 2;
} standard_timing[8] __attribute__ ((packed));
union {
struct vbe_edid_detailed_timing detailed_timing[4];
struct vbe_edid_monitor_descriptor monitor_descriptor[4];
} monitor_details __attribute__ ((packed));
unsigned char extension_flag;
unsigned char checksum;
unsigned char padding[128];
} __attribute__ ((packed));
#define VBE_LINEAR_FRAMEBUFFER 0x4000
/* Get VESA information. */
struct vbe_info *vbe_get_vbe_info();
/* Get information about a particular video mode, bitwise or with
VBE_LINEAR_FRAMEBUFFER to check if LFB version is supported. */
struct vbe_mode_info *vbe_get_mode_info(u_int16_t mode);
/* Check if EDID reads are supported, and do them. */
int vbe_get_edid_supported(int adapter);
struct vbe_edid1_info *vbe_get_edid_info(int adapter);
/* Get the current video mode, -1 on error. */
int32_t vbe_get_mode();
/* Set a new video mode, bitwise or with VBE_LINEAR_FRAMEBUFFER. */
void vbe_set_mode(u_int16_t mode);
/* Save/restore the SVGA state. Call free() on the state record when done. */
const void *vbe_save_svga_state();
void vbe_restore_svga_state(const void *state);
/* Get the ranges of values suitable for the attached monitor. */
void vbe_get_edid_ranges(struct vbe_edid1_info *edid,
unsigned char *hmin, unsigned char *hmax,
unsigned char *vmin, unsigned char *vmax);
/* Get a list of modelines that will work with this monitor. */
struct vbe_modeline *vbe_get_edid_modelines(int adapter);
#endif
#include "vesamode.h"
#ident "$Id: vesamode.c,v 1.1 1999/11/15 13:02:13 prigaux Exp $"
/* Known standard VESA modes. */
struct vesa_mode_t known_vesa_modes[] = {
/* VESA 1.0/1.1 ? */
{0x100, 640, 400, 256, "640x400x256"},
{0x101, 640, 480, 256, "640x480x256"},
{0x102, 800, 600, 16, "800x600x16"},
{0x103, 800, 600, 256, "800x600x256"},
{0x104, 1024, 768, 16, "1024x768x16"},
{0x105, 1024, 768, 256, "1024x768x256"},
{0x106, 1280, 1024, 16, "1280x1024x16"},
{0x107, 1280, 1024, 256,"1280x1024x256"},
{0x108, 80, 60, 16, "80x60 (text)"},
{0x109, 132, 25, 16, "132x25 (text)"},
{0x10a, 132, 43, 16, "132x43 (text)"},
{0x10b, 132, 50, 16, "132x50 (text)"},
{0x10c, 132, 60, 16, "132x60 (text)"},
/* VESA 1.2+ */
{0x10d, 320, 200, 32768, "320x200x32k"},
{0x10e, 320, 200, 65536, "320x200x64k"},
{0x10f, 320, 200, 16777216, "320x200x16m"},
{0x110, 640, 480, 32768, "640x480x32k"},
{0x111, 640, 480, 65536, "640x480x64k"},
{0x112, 640, 480, 16777216, "640x480x16m"},
{0x113, 800, 600, 32768, "800x600x32k"},
{0x114, 800, 600, 65536, "800x600x64k"},
{0x115, 800, 600, 16777216, "800x600x16m"},
{0x116, 1024, 768, 32768, "1024x768x32k"},
{0x117, 1024, 768, 65536, "1024x768x64k"},
{0x118, 1024, 768, 16777216, "1024x768x16m"},
{0x119, 1280, 1024, 32768, "1280x1024x32k"},
{0x11a, 1280, 1024, 65536, "1280x1024x64k"},
{0x11b, 1280, 1024, 16777216, "1280x1024x16m"},
/* VESA 2.0+ */
{0x120, 1600, 1200, 256, "1600x1200x256"},
{0x121, 1600, 1200, 32768, "1600x1200x32k"},
{0x122, 1600, 1200, 65536, "1600x1200x64k"},
{ 0, 0, 0, 0, ""},
};
struct vesa_timing_t known_vesa_timings[] = {
/* Source: VESA Monitor Timing Specifications 1.0 rev 0.8 */
{ 640, 350, 85, 31.500, { 640, 32, 64, 96, 350,32, 3, 60},
hsync_pos, vsync_neg, 37.861, 85.080},
{ 640, 400, 85, 31.500, { 640, 32, 64, 96, 400, 1, 3, 41},
hsync_neg, vsync_pos, 37.861, 85.080},
{ 720, 400, 85, 35.500, { 720, 36, 72, 108, 400, 1, 3, 42},
hsync_neg, vsync_pos, 37.861, 85.080},
{ 640, 480, 60, 25.175, { 640, 8, 96, 40, 480, 2, 2, 25},
hsync_neg, vsync_neg, 31.469, 59.940},
{ 640, 480, 72, 31.500, { 640, 16, 40, 120, 480, 1, 3, 20},
hsync_neg, vsync_neg, 37.861, 72.809},
{ 640, 480, 75, 31.500, { 640, 16, 64, 120, 480, 1, 3, 16},
hsync_neg, vsync_neg, 37.500, 75.000},
{ 640, 480, 85, 36.000, { 640, 56, 56, 80, 480, 1, 3, 25},
hsync_neg, vsync_neg, 43.269, 85.008},
{ 800, 600, 56, 36.000, { 800, 24, 72, 128, 600, 1, 2, 22},
hsync_pos, vsync_pos, 35.156, 56.250},
{ 800, 600, 60, 40.000, { 800, 40, 128, 88, 600, 1, 4, 23},
hsync_pos, vsync_pos, 37.879, 60.317},
{ 800, 600, 72, 50.000, { 800, 56, 120, 64, 600,37, 6, 23},
hsync_pos, vsync_pos, 48.077, 72.188},
{ 800, 600, 75, 49.500, { 800, 16, 80, 160, 600, 1, 3, 21},
hsync_pos, vsync_pos, 46.875, 75.000},
{ 800, 600, 85, 56.250, { 800, 32, 64, 152, 600, 1, 3, 27},
hsync_pos, vsync_pos, 53.674, 85.061},
{1024, 768, 43, 44.900, {1024, 8, 176, 56, 768, 0, 4, 20},
hsync_pos, vsync_pos, 35.522, 86.957},
{1024, 768, 60, 65.000, {1024, 24, 136, 160, 768, 3, 6, 29},
hsync_neg, vsync_neg, 48.363, 60.004},
{1024, 768, 70, 75.000, {1024, 24, 136, 144, 768, 3, 6, 29},
hsync_neg, vsync_neg, 56.476, 70.069},
{1024, 768, 75, 78.750, {1024, 16, 96, 176, 768, 1, 3, 28},
hsync_pos, vsync_pos, 60.023, 75.029},
{1024, 768, 85, 94.500, {1024, 48, 96, 208, 768, 1, 3, 36},
hsync_pos, vsync_pos, 68.677, 84.997},
{1152, 864, 70, 94.200, {1152, 32, 96, 192, 864, 1, 3, 46},
hsync_pos, vsync_pos, 0.000, 0.000},
{1152, 864, 75, 108.000, {1152, 64, 128, 256, 864, 1, 3, 32},
hsync_pos, vsync_pos, 67.500, 75.000},
{1152, 864, 85, 121.500, {1152, 64, 128, 224, 864, 1, 3, 43},
hsync_pos, vsync_pos, 0.000, 0.000},
{1280, 960, 60, 108.000, {1280, 96, 112, 312, 960, 1, 3, 36},
hsync_pos, vsync_pos, 60.000, 60.000},
{1280, 960, 85, 148.500, {1280, 64, 160, 224, 960, 1, 3, 47},
hsync_pos, vsync_pos, 85.398, 85.002},
{1280, 1024, 60, 108.000, {1280, 48, 112, 248, 1024, 1, 3, 38},
hsync_pos, vsync_pos, 63.981, 60.020},
{1280, 1024, 75, 135.000, {1280, 16, 144, 248, 1024, 1, 3, 38},
hsync_pos, vsync_pos, 79.976, 75.025},
{1280, 1024, 85, 157.500, {1280, 64, 160, 224, 1024, 1, 3, 44},
hsync_pos, vsync_pos, 91.146, 85.024},
{1600, 1200, 60, 162.000, {1600, 64, 192, 304, 1200, 1, 3, 46},
hsync_pos, vsync_pos, 75.000, 60.000},
{1600, 1200, 65, 175.500, {1600, 64, 192, 304, 1200, 1, 3, 46},
hsync_pos, vsync_pos, 81.250, 65.000},
{1600, 1200, 70, 189.000, {1600, 64, 192, 304, 1200, 1, 3, 46},
hsync_pos, vsync_pos, 87.500, 70.000},
{1600, 1200, 75, 202.500, {1600, 64, 192, 304, 1200, 1, 3, 46},
hsync_pos, vsync_pos, 93.750, 75.000},
{1600, 1200, 85, 229.500, {1600, 64, 192, 304, 1200, 1, 3, 46},
hsync_pos, vsync_pos, 106.250, 85.000},
{1792, 1344, 60, 204.750, {1792,128, 200, 328, 1344, 1, 3, 46},
hsync_neg, vsync_pos, 83.640, 60.000},
{1792, 1344, 75, 261.000, {1792, 96, 216, 352, 1344, 1, 3, 69},
hsync_neg, vsync_pos, 106.270, 74.997},
{1856, 1392, 60, 218.250, {1856, 96, 224, 352, 1392, 1, 3, 43},
hsync_neg, vsync_pos, 86.333, 59.995},
{1856, 1392, 75, 288.000, {1856,128, 224, 352, 1392, 1, 3,104},
hsync_neg, vsync_pos, 112.500, 75.000},
{1920, 1440, 60, 234.000, {1920,128, 208, 344, 1440, 1, 3, 56},
hsync_neg, vsync_pos, 90.000, 60.000},
{1920, 1440, 75, 297.000, {1920,144, 224, 352, 1440, 1, 3, 56},
hsync_neg, vsync_pos, 112.500, 75.000},
{ 0, 0, 0, 0.000, { 0, 0, 0, 0, 0, 0, 0, 0},
000000000, 000000000, 0.000, 0.000},
};
#ifndef vesamode_h
#define vesamode_h
#include <sys/types.h>
#ident "$Id: vesamode.h,v 1.1 1999/11/15 13:02:13 prigaux Exp $"
typedef enum { hsync_neg = 0, hsync_pos } hsync_t;
typedef enum { vsync_neg = 0, vsync_pos } vsync_t;
struct vesa_mode_t {
u_int16_t number;
u_int16_t x, y;
u_int32_t colors;
const char *text;
const char *modeline;
};
struct vesa_timing_t {
u_int16_t x, y;
float refresh;
float dotclock;
u_int16_t timings[8];
hsync_t hsync;
vsync_t vsync;
float hfreq;
float vfreq;
};
extern struct vesa_mode_t known_vesa_modes[];
extern struct vesa_timing_t known_vesa_timings[];
#endif /* vesamode_h */
# -*- coding: utf-8 -*-
### Modeline Calculation ###
def GetInt(name, dict, default=0):
_str = dict.get(name , default)
try:
return int(_str)
except:
return default
# _ GetFloat ___________________________________________________________
def GetFloat(name, dict, default=0.0):
_str = dict.get(name , default)
try:
return float(_str)
except:
return default
# _ ModeLine ___________________________________________________________
def ModeLine(dict={}):
'''
This routine will calculate XF86Config Modeline entries.
The Parameters are supplies as a dictionary due to the large number.
The Calculated values are also returned in dictionary form.
The parameter dictionary entries are:
hPix Horizontal displayed pixels Default: 1280)
hSync Horizontal sync in uSec Default: 1)
hBlank Horizontal blanking in uSec Default: 3)
vPix Vertical displayed pixels Default: 960)
vFreq Vertical scan frequency in Hz Default: 75)
vSync Vertical sync in uSec Default: 0)
vBlank Vertical blanking in uSec Default: 500)
v4x3 Constrain h/v to 4/3 Default: 0 (not constrained)
hRatio1 Horizontal front poarch ratio Default: 1)
hRatio2 Horizontal sync ratio Default: 4)
hRatio3 Horizontal back poarch ratio Default: 7)
vRatio1 Vertical front poarch ratio Default: 1)
vRatio2 Vertical sync ratio Default: 1)
vRatio3 Vertical back poarch ratio Default: 10)
If v4x3="1" vPix is ignored.
If any of the following:hSync, hBlanking, vSync, vBlanking
are not specified then they are set based on the ratios,
at a minimum is is best to specify either sync or blanking.
The return dictionary entries are:
The "entry" value is really all that is needed
entry Modeline entry string
These are the values that make up the modeline entry
dotClock Dot clock in MHz
hPix Horizontal displayed pixels
hFreq Horizontal scan frequency in Hz.
hTim1 Horizontal front poarch pixels
hTim2 Horizontal sync pixels
hTim3 Horizontal back poarch pixels
vPix Vertical displayed pixels
vFreq Vertical scan frequency in Hz.
vTim1 Vertical front poarch pixels
vTim2 Vertical sync pixels
vTim3 Vertical back poarch pixels
'''
results = {}
hPix = GetInt( "hPix" , dict, 1280)
hSync = GetFloat("hSync" , dict, 1)
hBlank = GetFloat("hBlank" , dict, 3)
hRatio1 = GetFloat("hRatio1" , dict, 1)
hRatio2 = GetFloat("hRatio2" , dict, 4)
hRatio3 = GetFloat("hRatio3" , dict, 7)
vPix = GetInt( "vPix" , dict, 960)
vFreq = GetFloat("vFreq" , dict, 75)
vSync = GetFloat("vSync" , dict, 0)
vBlank = GetFloat("vBlank" , dict, 500)
vRatio1 = GetFloat("vRatio1" , dict, 1)
vRatio2 = GetFloat("vRatio2" , dict, 1)
vRatio3 = GetFloat("vRatio3" , dict, 10)
if (dict.has_key("v4x3") == 0):
v4x3 = ""
else:
v4x3 = "checked"
vPix = int(hPix) / 4 * 3
vSyncUs = vSync / 1000000.0
vBlankUs = vBlank / 1000000.0
vRatioT = vRatio1 + vRatio2 + vRatio3
if ((vSyncUs > 0.0) and (vBlankUs > 0.0)):
vRatio2 = (vRatio1 + vRatio3) * (vSyncUs / (vBlankUs - vSyncUs))
vRatioT = vRatio1 + vRatio2 + vRatio3
elif ((vSyncUs > 0.0) and (vBlankUs <= 0.0)):
vBlankUs = vSyncUs * (vRatioT / vRatio2)
elif ((vSyncUs <= 0.0) and (vBlankUs > 0.0)):
vSyncUs = vBlankUs * (vRatio2 / vRatioT)
vBase = 1.0 / vFreq
vBase = (vPix / (vBase - vBlankUs)) * vBase
vBase = (vBase - vPix) / vRatioT
vTim1 = vPix + int((vBase * vRatio1) + 1.0)
vTim2 = vTim1 + int((vBase * vRatio2) + 1.0)
vTim3 = vTim2 + int((vBase * vRatio3) + 1.0)
hFreq = (vTim3 * vFreq)
hSyncUs = hSync / 1000000.0
hBlankUs = hBlank / 1000000.0
hPix = ((hPix + 7) / 8) * 8
hRatioT = hRatio1 + hRatio2 + hRatio3
if ((hSyncUs > 0.0) and (hBlankUs > 0.0)):
hRatio2 = (hRatio1 + hRatio3) * (hSyncUs / (hBlankUs - hSyncUs))
hRatioT = hRatio1 + hRatio2 + hRatio3
elif ((hSyncUs > 0.0) and (hBlankUs <= 0.0)):
hBlankUs = hSyncUs * (hRatioT / hRatio2)
elif ((hSyncUs <= 0.0) and (hBlankUs > 0.0)):
hSyncUshBlankUs = hBlankUs * (hRatio2 / hRatioT)
hBase = 1.0 / hFreq
hBase = (hPix / (hBase - hBlankUs)) * hBase
hBase = (hBase - hPix) / hRatioT
hTim1 = hPix + ((int((hBase * hRatio1)+8.0) / 8) * 8)
hTim2 = hTim1 + ((int((hBase * hRatio2)+8.0) / 8) * 8)
hTim3 = hTim2 + ((int((hBase * hRatio3)+8.0) / 8) * 8)
dotClock = (hTim3 * vTim3 * vFreq) / 1000000.0
hFreqKHz = hFreq / 1000.0
results = {}
results["entry"] = '''\
# %(hPix)dx%(vPix)d @ %(vFreq)dHz, %(hFreqKHz)6.2f kHz hsync
Mode "%(hPix)dx%(vPix)d"
DotClock %(dotClock)8.2f
HTimings %(hPix)d %(hTim1)d %(hTim2)d %(hTim3)d
VTimings %(vPix)d %(vTim1)d %(vTim2)d %(vTim3)d
EndMode\
''' % vars()
results["hPix"] = hPix
results["vPix"] = vPix
results["vFreq"] = vFreq
results["hFreq"] = hFreq
results["dotClock"] = dotClock
results["hTim1"] = hTim1
results["hTim2"] = hTim2
results["hTim3"] = hTim3
results["vTim1"] = vTim1
results["vTim2"] = vTim2
results["vTim3"] = vTim3
return results
def calcModeLine(w, h, vfreq):
vals = {}
vals["hPix"] = w
vals["vPix"] = h
vals["vFreq"] = vfreq
m = ModeLine(vals)
return m["entry"]
def calcFromEdid(edid):
dt = edid["detailed_timing"]
hActive = dt["horizontal_active"]
vActive = dt["vertical_active"]
hBlanking = dt["horizontal_blanking"]
vBlanking = dt["vertical_blanking"]
pixelClock = dt["pixel_clock"]
hTotal = hActive + hBlanking
vTotal = vActive + vBlanking
ret = {}
ret["mode"] = (hActive, vActive)
try:
ret["vfreq"] = float(pixelClock) / (hTotal * vTotal)
ret["hfreq"] = float(pixelClock) / (hTotal * 1000.0)
except ZeroDivisionError:
return
ret["dot_clock"] = pixelClock / 1000000.0
ret["htimings"] = (hActive, \
hActive + dt["hsync_offset"],\
hActive + dt["hsync_offset"] + dt["hsync_pulse_width"], \
hTotal)
ret["vtimings"] = (vActive, \
vActive + dt["vsync_offset"],\
vActive + dt["vsync_offset"] + dt["vsync_pulse_width"], \
vTotal)
flags = dt["flags"]
ret["flags"] = []
if flags["interlaced"] or flags["separate_sync"]:
if flags["interlaced"]:
ret["flags"].append("Interlace")
if flags["hsync_positive"]:
ret["flags"].append("+HSync")
else:
ret["flags"].append("-HSync")
if flags["vsync_positive"]:
ret["flags"].append("+VSync")
else:
ret["flags"].append("-VSync")
return ret
# -*- coding: utf-8 -*-
import dbus.types
trueList = ("1", "on", "true", "yes", "enable")
falseList = ("0", "off", "false", "no", "disable")
xBool = {True: "true", False: "false"}
class unquoted(str):
pass
class XorgEntry:
def __init__(self, line = ""):
line = line.strip()
if line == "":
self.key = ""
self.values = []
return
v = line.split(None, 1)
self.key = v.pop(0)
if v:
line = v[0].strip()
else:
line = ""
self.values = []
while line:
if line[0] == '"':
end = line.index('"', 1)
self.values.append(line[1:end])
line = line[end+1:].lstrip()
elif line[0] == "#":
break
else:
v = line.split(None, 1)
arg = v.pop(0)
if v:
line = v[0].strip()
else:
line = ""
if arg[0] == "0" and len(arg) > 1:
self.values.append(unquoted(arg))
else:
try:
self.values.append(int(arg))
except ValueError:
self.values.append(unquoted(arg))
def __str__(self):
s = "%s\t%s" % (self.key, entryFormat(self.values))
return s
def __repr__(self):
return "<XorgEntry: %s>" % str(self)
def entryFormat(values):
s = ""
for v in values:
if type(v) in (str, unicode, dbus.types.String):
s += ' "%s"' % v
else:
s += " %s" % v
return s.lstrip()
class XorgSection:
def __init__(self, name):
self.name = name
self.sections = []
self.entries = []
self.options = {}
def entry(self, key):
for entry in self.entries:
if entry.key == key: # Comparisons must be case-insensitive; but ignore for now
return entry
return None
def __repr__(self):
return "<XorgSection '%s'>" % self.name
def getEntries(self, key):
return tuple(x for x in self.entries if x.key == key)
def getSections(self, *names):
return tuple(x for x in self.sections if x.name in names)
def get(self, key, index = 0, *defaults):
entry = self.entry(key)
if entry:
return entry.values[index]
else:
return defaults
def set(self, key, *values):
entry = self.entry(key)
if entry:
entry.values = values
else:
self.add(key, *values)
def add(self, key, *values):
entry = XorgEntry(key)
entry.values = values
self.entries.append(entry)
class XorgParser:
def __init__(self):
self.sections = []
self.screens = []
self.inputDevices = []
def parseFile(self, filePath):
section = None
stack = [self]
lines = file(filePath).readlines()
for line in lines:
e = XorgEntry(line)
key = e.key.lower()
if key == "" or key[0] == "#":
continue
elif key in ("section", "subsection"):
section = XorgSection(e.values[0])
stack[-1].sections.append(section)
stack.append(section)
elif section:
if key in ("endsection", "endsubsection"):
stack.pop()
if stack:
section = stack[-1]
else:
section = None
elif e.values and key == "option":
key = e.values.pop(0)
if e.values:
value = e.values[0]
else:
value = "true"
section.options[key] = value
else:
section.entries.append(e)
def getSections(self, *names):
secs = tuple(x for x in self.sections if x.name in names)
#return secs
if secs:
return secs
else:
secs = []
for name in names:
sec = XorgSection(name)
secs.append(sec)
self.sections.append(sec)
return secs # :)
def toString(self):
s = ""
def writeSection(sect, dep):
s = '%sSubSection "%s"\n' % ("\t" * dep, sect.name)
# Entries except 'Option'
for e in sect.entries:
s += "%s%s\t%s\n" % ("\t" * (dep+1), e.key, entryFormat(e.values))
# Options
for k, v in sect.options.items():
ent = XorgEntry('Option "%s"' % k)
ent.values.append(v)
s += "%s%s\n" % ("\t" * (dep+1), ent)
# Sub sections
for sec in sect.sections:
s += writeSection(sec, dep + 1)
s += "%sEndSubSection\n" % "\t" * dep
return s
for section in self.sections:
s += 'Section "%s"\n' % section.name
for e in section.entries:
s += "\t%s\t%s\n" % (e.key, entryFormat(e.values))
for k, v in section.options.items():
ent = XorgEntry('Option "%s"' % k)
ent.values.append(v)
s += "\t%s\n" % ent
for sec in section.sections:
s += writeSection(sec, 1)
s += "EndSection\n\n"
return s.expandtabs(4)
This diff is collapsed.
# -*- coding: utf-8 -*-
import os
import subprocess
import time
import sha
xorg_lock = "/tmp/.X0-lock"
def atoi(s):
# python's int() borks when given non integer characters
t = ""
for c in s.lstrip():
if c in "0123456789":
t += c
else:
break
try:
ret = int(t)
except:
ret = 0
return ret
def unlink(path):
try:
os.unlink(path)
except:
pass
def touch(_file):
try:
if not os.path.exists(_file):
file(_file, "w").close()
except:
pass
def backup(_file):
try:
if os.path.exists(_file):
os.rename(_file, "%s-backup" % _file)
return True
except:
return False
def getDate():
return time.ctime()
def getChecksum(_data):
return sha.sha(_data).hexdigest()
def getKernelOpt(cmdopt=None):
if cmdopt:
for cmd in "".join(loadFile("/proc/cmdline")).split():
if cmd.startswith("%s=" % cmdopt):
return cmd[len(cmdopt)+1:].split(",")
else:
return "".join(loadFile("/proc/cmdline")).split()
return ""
def capture(*cmd):
a = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return a.communicate()
def run(*cmd):
f = file("/dev/null", "w")
return subprocess.call(cmd, stdout=f, stderr=f)
def loadFile(_file):
try:
f = file(_file)
d = [a.strip() for a in f]
d = (x for x in d if x and x[0] != "#")
f.close()
return d
except:
return []
def lremove(str, pre):
if str.startswith(pre):
return str[len(pre):]
return str
def sysValue(path, dir, _file):
f = file(os.path.join(path, dir, _file))
data = f.read().rstrip('\n')
f.close()
return data
def xisrunning():
return os.path.exists(xorg_lock)
def parseMode(mode):
m = mode.split("-", 1)
res = m.pop(0)
try:
w, h = map(int, res.split("x", 1))
except:
return None, None
depth = None
if m:
try:
d = int(m[0])
if d in (16, 24):
depth = d
else:
res = None
except ValueError:
res = None
return res, depth
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment