Kaydet (Commit) 251a03c9 authored tarafından Suleyman Poyraz's avatar Suleyman Poyraz

Python3'e uygun olarak duzenlendi, eklendi filan

üst db4bb8ce
This diff is collapsed.
COMAR API package offers modules for accessing COMAR over D-Bus without pain and
common methods/classes for COMAR scripts.
SCOM API package offers modules for accessing COMAR over D-Bus without pain and
common methods/classes for SCOM scripts.
Here are some examples for accessing COMAR:
Here are some examples for accessing SCOM:
import comar
link = comar.Link()
import scom
link = scom.Link()
# Localize strings
link.setLocale()
......@@ -28,8 +28,8 @@ Asynchronous calls:
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
mainloop = gobject.MainLoop()
import comar
link = comar.Link()
import scom
link = scom.Link()
# Localize strings
link.setLocale()
......@@ -40,22 +40,22 @@ Asynchronous calls:
# Make an asynchronous call to get service information
def handler(package, exception, result):
if exception:
print "%s error: %s" % (package, exception)
print ("%s error: %s" % (package, exception))
else:
print "%s result: %s" % (package, result)
print ("%s result: %s" % (package, result))
link.System.Service.info(async=handler)
mainloop.run()
Connecting COMAR service on alternate destination:
Connecting SCOM service on alternate destination:
import comar
link = comar.Link(alternate=True)
import scom
link = scom.Link(alternate=True)
This will simply try to connect tr.org.pardus.comar2 instead
of tr.org.pardus.comar
This will simply try to connect tr.org.pardus.scom2 instead
of tr.org.pardus.scom
Connecting to alternative DBus server:
import comar
link = comar.Link(socket="/mnt/target/var/run/dbus/system_bus_socket")
import scom
link = scom.Link(socket="/mnt/target/var/run/dbus/system_bus_socket")
......@@ -5,7 +5,7 @@ import sys
from qt import *
import comar
import scom
from dbus.mainloop.qt3 import DBusQtMainLoop
import mainform
......@@ -14,7 +14,7 @@ class Window(mainform.mainForm):
def __init__(self, parent=None):
mainform.mainForm.__init__(self, parent)
self.link = comar.Link()
self.link = scom.Link()
self.connect(self.buttonServices, SIGNAL("clicked()"), self.getServices)
......
......@@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
import sys
import comar
import scom
import mainform
from PyQt4 import QtGui
......@@ -19,7 +19,7 @@ class Window(QtGui.QWidget):
self.ui.setupUi(self)
# Call Comar
self.link = comar.Link()
self.link = scom.Link()
# Connect button click event to getServices method
self.connect(self.ui.buttonServices, SIGNAL("clicked()"), self.getServices)
......@@ -31,7 +31,7 @@ class Window(QtGui.QWidget):
self.ui.textServices.append("%s - %s - %s - %s" % (package, serviceName, serviceDesc, serviceState))
def getServices(self):
# Get service list from comar link
# Get service list from scom link
self.link.System.Service.info(async=self.handleServices)
def main():
......
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009, TUBITAK/UEKAE
# Copyright (C) 2016-2018, AquilaNipalensis
#
# 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
......
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009, TUBITAK/UEKAE
# Copyright (C) 2016-2018, AquilaNipalensis
#
# 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
......
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009, TUBITAK/UEKAE
# Copyright (C) 2016-2018, AquilaNipalensis
#
# 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
......
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009, TUBITAK/UEKAE
# Copyright (C) 2016-2018, AquilaNipalensis
#
# 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
......
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2007, TUBITAK/UEKAE
# Copyright (C) 2016-2017, AquilaNipalensis
#
# 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
......
Suleyman POYRAZ < nipalensisaquila [at] gmail.com >
AquilaNipalensis (Suleyman POYRAZ) < nipalensisaquila [at] gmail.com >
Mudur
------
Mudur is the first component of Pardus initialization system. It's the main startup script which is
called by init and handles basic initialization and shutdown.
# mudur
sysvinit booting scripts replacement for Lupus
Current Maintainer:
Fatih Aşıcı <fatih [at] pardus.org.tr>
Other Developers:
Onur Küçük <onur [at] pardus.org.tr>
2010-03-03 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/config.py:
Use "Disable" option for disable outputs.
2010-01-06 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg-cli:
-d parameter can take an empty string as the driver name
that means the driver will be selected by the X server.
2009-11-17 Fatih Aşıcı <fatih@pardus.org.tr>
* data/DriversDB:
Remove nvidia71 driver as it doesn't work with new X servers.
* sorg/hwdata.py:
Remove names of old nvidia packages.
2009-10-30 Fatih Aşıcı <fatih@pardus.org.tr>
* data/DriversDB:
Add new NVIDIA cards.
2009-10-26 Fatih Aşıcı <fatih@pardus.org.tr>
* data/DriversDB:
Add new ATI cards.
2009-05-01 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/probe.py:
Implement a simplified version of getPrimaryCard.
2009-04-23 Fatih Aşıcı <fatih@pardus.org.tr>
* setup.py:
Do not install modprobe.d config file.
2009-03-30 Fatih Aşıcı <fatih@pardus.org.tr>
* data/DriversDB:
Prefer nvidia-drivers package for 10de:0242.
2009-03-28 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/parser.py:
Do case-insensitive comparison for entry names
2009-03-20 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/config.py, zorg/consts.py, zorg/hwdata.py, zorg/probe.py:
- Refactor variable names to increase consistency.
- Add configuredBus function to get last configured card by
sorg. This will be used at boot.
- Use an empty string for xkb variant as not all layouts have
"basic" variant.
* sorg/utils.py:
- Cleanup unused utils.
* setup.py:
- Get config and data dirs from sorg module instead of
hardcoding.
2009-03-08 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/utils.py:
- Improve backup function to keep last 3 backups.
- Use pardus-python's new get_kernel_option function. Remove
the internal one.
* sorg/config.py, zorg/consts.py, zorg/probe.py:
- Let Xorg decide most of the configurations. Make
Screen, Display, Layout and Monitor sections optional.
- Disable framebuffer size calculation since it tries
to parse mode name and mode names do not have to be in
format "WidthxHeight". Also drivers should be clever
to calcute fb size.
- Add a flag to indicate the initial config.
- Remove monitor query stuff.
- Cleanup unused bits.
* sorg/ddc, zorg/modeline.py:
- Remove ddc and modeline modules.
2009-03-05 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/config.py:
- Do not create InputDevice sections. We will use
new input hotplug mechanism for all input devices.
- Do not create Files section. We will use
catalogue paths.
- Do not create redundant dri section.
* sorg/__init__.py:
- Remove unused __all__ list.
2009-02-19 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/hwdata.py:
Copy hwdata module from display manager.
Add vboxvideo driver to the driver list.
2009-02-02 Fatih Aşıcı <fatih@pardus.org.tr>
* data/DriversDB, sorg/{config,probe}.py:
Add support for VirtualBox video and mouse drivers.
2009-01-22 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/parser.py:
Fix a regression introduced with
type/instance changes.
2009-01-21 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/probe.py:
Fixed framebuffer device node name.
* data/DriversDB:
Added new PCI IDs for nvidia-180.
2008-11-01 Fatih Aşıcı <fatih@pardus.org.tr>
* data/DriversDB:
Renamed nvidia packages.
Added new cards.
* data/modprobe.d/sorg:
Added new module names for nvidia.
* sorg/__init__.py:
Bumped version to 1.1.1.
2008-10-04 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/__init__.py:
Bumped version to 1.1.
* sorg/config.py:
Added support to create InputDevice sections
for wacom devices.
2008-09-24 Fatih Aşıcı <fatih@pardus.org.tr>
* sorg/probe.py:
Added a high timeout value for dbus calls since
enabling a driver package might take a long time on slow
machines.
2008-09-17 Fatih Aşıcı <fatih@pardus.org.tr>
* AUTHORS, ChangeLog:
Added AUTHORS and ChangeLog.
recursive-include sorg/ddc *.h
include sorg-loadmodule
include data/*DB data/modprobe.d/sorg
include AUTHORS ChangeLog COPYING README TODO
What is sorg?
-------------
sorg consists of python scripts and modules which
automate the configuration of Xorg.
Requirements
------------
* sulin-python > 0.3.3
Installing & Running
--------------------
1. Register the Scom script comes with sorg package:
hav register Xorg.Display sorg scom/xorg.display.py
2. Install:
./setup.py install --install-lib=/usr/lib/sulin
3. Run: sorg-cli
sorg TODO List
==============
Legend:
- Todo
? Not determined if/how we have to do
/ In progress
+ Accomplished
Scom Methods:
/ configuration setup on boot
+ check config files
+ check hardware changes
+ read kernel options (xorg=...)
+ do pending jobs
? compatibility check between kernel and xorg driver versions (e.g. nvidia-kernel and nvidia-glx issue)
- 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:
- try to get preferred resolution and use it by default
- parser to get monitor vendor/model list
Command Line Tool:
- test option
? DPI selection
? Xorg log file verbosity selection
? bug report option/tool
This diff is collapsed.
This diff is collapsed.
install fglrx /sbin/sorg-loadmodule $CMDLINE_OPTS
install nvidia /sbin/sorg-loadmodule $CMDLINE_OPTS
install nvidia_new /sbin/sorg-loadmodule $CMDLINE_OPTS
install nvidia_old /sbin/sorg-loadmodule $CMDLINE_OPTS
install nvidia_173 /sbin/sorg-loadmodule $CMDLINE_OPTS
install nvidia_177 /sbin/sorg-loadmodule $CMDLINE_OPTS
#!/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 as xxx_todo_changeme:
(errno, str) = xxx_todo_changeme.args
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 tmp[1] in manufacturers:
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 section in manufacturers:
# 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 install in instsections:
instsections[install].append ((section, id))
else:
instsections[install] = [ (section, id) ]
if section not in monitors:
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 key in sync_keys:
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 section in instsections:
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 registry in regsections:
regsections[registry].append (section)
else:
regsections[registry] = [ section ]
# these are the actual AddReg entries. Look up in our table
# to find which
elif section in regsections:
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 list(manufacturers.keys()):
for monitor in list(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 -*-
import os
from distutils.core import setup
from distutils.command.install import install
import sorg
from sorg import consts
class Install(install):
def run(self):
install.run(self)
if not self.root:
self.root = "/"
target = os.path.join(self.root, consts.config_dir.lstrip("/"))
if not os.path.exists(target):
os.makedirs(target, 0o755)
setup(name="sorg",
version=sorg.versionString(),
description="Python Modules for sorg",
license="GNU GPL2",
url="http://www.pardus.org.tr/",
packages = ["sorg"],
scripts = ["sorg-cli", "inf2mondb"],
data_files = [
(consts.data_dir, ["data/DriversDB", "data/MonitorsDB"]),
("/sbin", ["sorg-loadmodule"]),
],
cmdclass = {"install": Install}
)
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2010 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 sys
import optparse
import scom
import sorg
from sorg.consts import package_sep
from sorg.utils import *
sorg_info = " Xorg AutoConfiguration tool"
link = scom.Link()
def safe():
if link.Xorg.Display["sorg"].safeConfig():
link.Xorg.Display["sorg"].syncConfigs()
print("Initialized a safe configuration using VESA driver.")
else:
print("Failed to create a safe configuration with VESA driver.")
def probe(opts):
if link.Xorg.Display["sorg"].initialConfig():
link.Xorg.Display["sorg"].syncConfigs()
print("Created an initial configuration for your video device.")
else:
print("An error occured while creating an initial configuration.")
def setDriver(driver):
# Needed for compatibility with old sorg versions
oldnames = {
"fglrx/ati-drivers": "fglrx",
"nvidia/xorg-video-nvidia96": "nvidia96",
"nvidia/xorg-video-nvidia173": "nvidia173",
"nvidia/xorg-video-nvidia185": "nvidia185",
}
if driver in oldnames:
driver = oldnames[driver]
if package_sep in driver:
drv, pkg = driver.split(package_sep, 1)
if pkg.replace("-", "_") not in list(link.Xorg.Driver):
print("Package is not installed: %s" % pkg)
sys.exit(1)
link.Xorg.Display["sorg"].setDriver(driver)
link.Xorg.Display["sorg"].syncConfigs()
if driver:
print("The video driver is set to '%s'." % driver)
else:
print("The video driver will be selected by the X server.")
if __name__ == "__main__":
parser = optparse.OptionParser(description = "%s version %s"
% (sorg_info, zorg.versionString()))
parser.add_option("-s", "--safe", action="store_true",
dest="safe", default=False,
help="setup VESA 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("-d", "--driver", action="store", type="string",
dest="driver", default=None, metavar="DRIVER[%sPACKAGE]" % package_sep,
help="set video card driver to DRIVER")
parser.add_option("-k", "--keymap", action="store", type="string",
dest="keymap", default=None, metavar="LAYOUT[/VARIANT]",
help="changes keyboard map")
opts, args = parser.parse_args()
if opts.safe:
safe()
elif opts.probe:
probe(opts)
elif opts.driver is not None:
setDriver(opts.driver)
elif opts.keymap:
if "/" in opts.keymap:
layout, variant = opts.keymap.split("/", 1)
else:
layout, variant = opts.keymap, ""
link.Xorg.Display["sorg"].setKeymap(layout, variant)
else:
parser.print_help()
#!/bin/sh
kernel_module=/var/lib/sorg/kernel_module
if [ -e $kernel_module ]; then
/sbin/modprobe --ignore-install $(cat $kernel_module) $@
fi
#-*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009, 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__ = "2.0.4"
def versionString():
return __version__
# -*- coding: utf-8 -*-
import os
import dbus
import scom
import ciksemel
from sorg import consts
from sorg.parser import *
from sorg.probe import VideoDevice, Monitor, Output
from sorg.utils import *
def saveXorgConfig(card):
parser = XorgParser()
secFlags = XorgSection("ServerFlags")
secDevice = XorgSection("Device")
secScr = XorgSection("Screen")
secLay = XorgSection("ServerLayout")
parser.sections = [
secFlags,
secDevice,
secScr,
secLay
]
if jailEnabled():
jailOpts = {
"DontVTSwitch" : "true",
}
secFlags.options.update(jailOpts)
# Device section
secDevice.set("Identifier", "VideoCard")
drvInfo = card.driverInfo()
if drvInfo:
secDevice.set("Driver", drvInfo["xorg-module"])
if card.driver == "fglrx":
card.depth = 24
# Monitor sections
for name, output in list(card.outputs.items()):
identifier = "Monitor[%s]" % name
monSec = XorgSection("Monitor")
parser.sections.append(monSec)
monSec.set("Identifier", identifier)
if name in card.monitors:
monSec.set("VendorName", card.monitors[name].vendor)
monSec.set("ModelName", card.monitors[name].model)
monSec.set("HorizSync", unquoted(card.monitors[name].hsync))
monSec.set("VertRefresh", unquoted(card.monitors[name].vref ))
secDevice.options["Monitor-%s" % name] = identifier
if output.ignored:
monSec.options["Ignore"] = "true"
continue
if output.enabled:
monSec.options["Enable"] = "true"
else:
monSec.options["Disable"] = "true"
if output.mode:
monSec.options["PreferredMode"] = output.mode
if output.refresh_rate:
monSec.options["TargetRefresh"] = output.refresh_rate
if output.rotation:
monSec.options["Rotate"] = output.rotation
if output.right_of:
monSec.options["RightOf"] = output.right_of
elif output.below:
monSec.options["Below"] = output.below
# Screen section
secScr.set("Identifier", "Screen")
secScr.set("Device", "VideoCard")
if card.depth:
secScr.set("DefaultDepth", card.depth)
if "default" in card.outputs:
output = card.outputs["default"]
secScr.set("Monitor", "Monitor[default]")
if output.mode:
subsec = XorgSection("Display")
if card.depth:
subsec.set("Depth", card.depth)
subsec.set("Modes", output.mode, "800x600", "640x480")
secScr.sections = [subsec]
# Layout section
secLay.set("Identifier", "Layout")
secLay.set("Screen", "Screen")
# If this driver has an Xorg.Driver script,
# call its methods to update sections.
pkg = drvInfo.get("package")
if pkg:
link = scom.Link()
opts = dbus.Dictionary(secDevice.options, signature="ss")
try:
secDevice.options = link.Xorg.Driver[pkg].getDeviceOptions(
card.bus_id, opts)
except dbus.DBusException:
pass
# Backup and save xorg.conf
backup(consts.xorg_conf_file)
f = open(consts.xorg_conf_file, "w")
f.write(parser.toString())
f = open(consts.configured_bus_file, "w")
f.write(card.bus_id)
def configuredBus():
try:
return open(consts.configured_bus_file).read()
except IOError:
return ""
def addTag(p, name, data):
t = p.insertTag(name)
t.insertData(data)
def getDeviceInfo(busId):
if not os.path.exists(consts.config_file):
return
doc = ciksemel.parse(consts.config_file)
cardTag = None
for tag in doc.tags("Card"):
if tag.getAttribute("busId") == busId:
cardTag = tag
break
if not cardTag:
return
device = VideoDevice(busId=busId)
device.saved_vendor_id = cardTag.getTagData("VendorId")
device.saved_product_id = cardTag.getTagData("ProductId")
driver = cardTag.getTagData("Driver")
activeConfigTag = cardTag.getTag("ActiveConfig")
if driver:
device.driver = driver
elif activeConfigTag:
driver = activeConfigTag.getTagData("Driver")
if driver:
device.driver = driver
depth = cardTag.getTagData("Depth")
if depth:
device.depth = int(depth)
def addMonitor(output, tag):
mon = Monitor()
mon.vendor = tag.getTagData("Vendor") or ""
mon.model = tag.getTagData("Model") or "Unknown Monitor"
mon.hsync = tag.getTagData("HorizSync") or mon.hsync
mon.vref = tag.getTagData("VertRefresh") or mon.vref
device.monitors[output] = mon
# Get output info
outputsTag = cardTag.getTag("Outputs")
if outputsTag:
for outputTag in outputsTag.tags("Output"):
name = outputTag.getAttribute("name")
output = Output(name)
device.outputs[name] = output
enabled = outputTag.getTagData("Enabled")
if enabled:
output.setEnabled(enabled == "true")
ignored = outputTag.getTagData("Ignored")
if ignored:
output.setIgnored(ignored == "true")
mode = outputTag.getTagData("Mode") or ""
rate = outputTag.getTagData("RefreshRate") or ""
output.setMode(mode, rate)
rotation = outputTag.getTagData("Rotation")
if rotation:
output.setOrientation(rotation)
rightOf = outputTag.getTagData("RightOf")
below = outputTag.getTagData("Below")
if rightOf:
output.setPosition("RightOf", rightOf)
elif below:
output.setPosition("Below", below)
monitorTag = outputTag.getTag("Monitor")
if monitorTag:
addMonitor(name, monitorTag)
return device
def saveDeviceInfo(card):
if not os.path.exists(consts.config_dir):
os.mkdir(consts.config_dir, 0o755)
try:
doc = ciksemel.parse(consts.config_file)
except OSError:
doc = ciksemel.newDocument("ZORG")
for tag in doc.tags("Card"):
if tag.getAttribute("busId") == card.bus_id:
tag.hide()
break
cardTag = doc.insertTag("Card")
cardTag.setAttribute("busId", card.bus_id)
addTag(cardTag, "VendorId", card.vendor_id)
addTag(cardTag, "ProductId", card.product_id)
if card.driver:
addTag(cardTag, "Driver", card.driver)
if card.depth:
addTag(cardTag, "Depth", str(card.depth))
# Save output info
outputs = cardTag.insertTag("Outputs")
for name, output in list(card.outputs.items()):
out = outputs.insertTag("Output")
out.setAttribute("name", name)
addTag(out, "Enabled", "true" if output.enabled else "false")
addTag(out, "Ignored", "true" if output.ignored else "false")
if output.mode:
addTag(out, "Mode", output.mode)
if output.refresh_rate:
addTag(out, "RefreshRate", output.refresh_rate)
if output.rotation:
addTag(out, "Rotation", output.rotation)
if output.right_of:
addTag(out, "RightOf", output.right_of)
if output.below:
addTag(out, "Below", output.below)
if name in card.monitors:
mon = card.monitors[name]
monitor = out.insertTag("Monitor")
addTag(monitor, "Vendor", mon.vendor)
addTag(monitor, "Model", mon.model)
addTag(monitor, "HorizSync", mon.hsync)
addTag(monitor, "VertRefresh", mon.vref)
f = open(consts.config_file, "w")
f.write(doc.toPrettyString().replace("\n\n", ""))
def getKeymap():
layout = None
variant = ""
try:
doc = ciksemel.parse(consts.config_file)
keyboard = doc.getTag("Keyboard")
if keyboard:
layout = keyboard.getTagData("Layout")
variant = keyboard.getTagData("Variant") or ""
except OSError:
pass
if not layout:
from pardus.localedata import languages
try:
language = file("/etc/mudur/language").read().strip()
except IOError:
language = "en"
if language not in languages:
language = "en"
keymap = languages[language].keymaps[0]
layout = keymap.xkb_layout
variant = keymap.xkb_variant
return layout, variant
def saveKeymap(layout, variant=""):
if not os.path.exists(consts.config_dir):
os.mkdir(consts.config_dir, 0o755)
try:
doc = ciksemel.parse(consts.config_file)
except OSError:
doc = ciksemel.newDocument("ZORG")
keyboardTag = doc.getTag("Keyboard")
if keyboardTag:
keyboardTag.hide()
keyboardTag = doc.insertTag("Keyboard")
keyboardTag.insertTag("Layout").insertData(layout)
if variant:
keyboardTag.insertTag("Variant").insertData(variant)
f = file(consts.config_file, "w")
f.write(doc.toPrettyString().replace("\n\n", ""))
#!/usr/bin/python
# -*- coding: utf-8 -*-
from os.path import join
config_dir = "/var/lib/sorg"
data_dir = "/usr/share/X11"
modules_dir = "/usr/lib/xorg/modules"
xorg_conf_file = "/etc/X11/xorg.conf"
config_file = join(config_dir, "config.xml")
configured_bus_file = join(config_dir, "configured_bus")
drivers_file = join(data_dir, "DriversDB")
monitors_file = join(data_dir, "MonitorsDB")
xkb_symbols_dir = join(data_dir, "xkb/symbols")
drivers_dir = join(modules_dir, "drivers")
package_sep = "/"
# -*- coding: utf-8 -*-
import scom
import sorg.probe
from sorg import consts
from sorg.utils import *
drivers = {
"apm": "Alliance ProMotion cards, including AT24, AT3D, and AT25",
"ark": "ARK Logic chipsets",
"ast": "ASpeedTech chipsets",
"ati": "ATI Mach8, Mach32, Mach64, and RageXL cards",
"chips": "Chips and Technologies chipsets, including CT655xx, CT64xxx, CT68xxx, and CT690x0",
"cirrus": "Cirrus CL-GD54xx/7548 cards",
"cyrix": "Cyrix MediaGX, MediaGXi, and MediaGXm processors",
"fbdev": "Linux FrameBuffer",
"fglrx/ati-drivers":
"Drivers written by AMD(ATI) for ATI graphics cards",
"glint": "3DLabs/Texas Instruments GLINT and Permedia cards",
"i128": "Number 9 Imagine 128 cards",
"i740": "Intel I740 chipset",
"intel": "Intel Integrated Graphics Chipsets, including i810, i815, 830M, 845G, 852GM, 855GM, 865G, 915G, 915GM, and 945GM",
"imstt": "Integrated Micro Solutions Twin Turbo 128",
"mga": "Matrox Millennium, Mystique, Millennium II, G100, G200, G400, G450, G550",
"neomagic": "NeoMagic MagicGraph 128, 256",
"newport": "SGI Indy/Indigo2 Newport card",
"nsc": "National Semiconductors Geode Processor",
"nv": "nVidia Riva 128, RIVA TNT, GeForce, nForce, and QUADRO cards",
"openchrome": "VIA/S3G UniChrome, UniChrome Pro and Chrome9 graphics chipsets",
"r128": "ATI Rage128 cards, including Rage Fury, XPERT 128, and XPERT 99",
"radeon": "ATI Radeon cards, including Radeon Mobility and FireGL",
"radeonhd": "AMD GPG r5xx/r6xx Chipsets",
"rendition": "Rendition/Micron Verite cards, including Diamond Stealth II S220",
"s3": "S3 964, 968, Trio, Aurora64, and Trio64 cards",
"s3virge": "S3 ViRGE and Trio3D cards",
"savage": "S3 Savage, SuperSavage, Twister, and ProSavage chipsets",
"siliconmotion":"Silicon Motion Lynx and Cougar chipsets",
"sis": "Silicon Integrated Systems SiS chipsets",
"sisusb": "Silicon Integrated Systems SiS315E/PRO USB adpater",
"sunbw2": "Sun BW2 framebuffer",
"suncg14": "Sun CG14 framebuffer",
"suncg3": "Sun CG3 framebuffer",
"suncg6": "Sun GX/Turbo GX (cgsix) framebuffer",
"sunffb": "Sun Creator, Creator 3D, Elite 3D framebuffer",
"sunleo": "Sun Leo (ZX) framebuffer",
"suntcx": "Sun TCX framebuffer",
"tdfx": "3Dfx Voodoo Banshee, Voodoo 3, Voodoo 4, Voodoo 5 cards",
"tga": "DEC TGA chipset",
"trident": "Trident Blade, CyberBlade, 3DImage, ProVidia, TGUI, and Cyber9xxx cards",
"tseng": "Tseng Labs ET4000, ET6000, and ET6100 cards",
"vboxvideo/virtualbox-guest-utils":
"Video driver for VirtualBox guests",
"vesa": "Generic VESA-compliant video cards",
"vga": "Generic VGA video cards",
"via": "VIA Unichrome (CLE266, KM400/KN400, K8M800/K8N800, PM8X0, CN400) chipsets",
"vmware": "VMWare virtual video cards",
"voodoo": "Voodoo1 and Voodoo2 cards"
}
driverPackages = {
"fglrx": "xorg-video-fglrx",
"nvidia96": "xorg-video-nvidia96",
"nvidia173": "xorg-video-nvidia173",
"nvidia-current": "xorg-video-nvidia-current"
}
def getCompatibleDriverNames(vendor_id, product_id):
pci_id = vendor_id + product_id
drvlist = []
for line in loadFile(consts.drivers_file):
if line.startswith(pci_id):
drvlist = line.rstrip("\n").split(" ")[1:]
break
if "vesa" not in drvlist:
drvlist.append("vesa")
if "fbdev" not in drvlist:
drvlist.append("fbdev")
return drvlist
def getAvailableDriverNames():
drvlist = []
link = scom.Link()
availablePackages = list(link.Xorg.Driver)
availableDrivers = sorg.probe.listAvailableDrivers()
packages = [x.split(consts.package_sep) for x in list(drivers.keys()) if consts.package_sep in x]
for d in availableDrivers:
drvlist.append(d)
for drv, pkg in packages:
if pkg.replace("-", "_") in availablePackages:
d = drv + consts.package_sep + pkg
drvlist.append(d)
if drv in drvlist:
drvlist.remove(drv)
return drvlist
def getMonitorInfos():
genericList = {}
vendorList = {}
for line in loadFile(consts.monitors_file):
monitor = line.split(";")
if len(monitor) == 5:
monitor.append('0')
monitor = list(map(str.strip, monitor))
if len(monitor) == 6:
if "Generic" in monitor[0]:
if not monitor[0] in genericList:
genericList[monitor[0]] = [{ "model": monitor[1],
"eisa_id": monitor[2],
"hsync": monitor[3],
"vref": monitor[4],
"is_dpms": monitor[5]
}]
else:
genericList[monitor[0]].extend([{"model": monitor[1],
"eisa_id": monitor[2],
"hsync": monitor[3],
"vref": monitor[4],
"is_dpms": monitor[5]
}])
elif not monitor[0] in vendorList:
vendorList[monitor[0]] = [{ "model": monitor[1],
"eisa_id": monitor[2],
"hsync": monitor[3],
"vref": monitor[4],
"is_dpms": monitor[5]
}]
else:
vendorList[monitor[0]].extend([{"model": monitor[1],
"eisa_id": monitor[2],
"hsync": monitor[3],
"vref": monitor[4],
"is_dpms": monitor[5]
}])
return genericList, vendorList
# -*- coding: utf-8 -*-
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 isinstance(v, str) and not isinstance(v, unquoted):
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):
key = key.lower()
for entry in self.entries:
if entry.key.lower() == key:
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, default = None):
entry = self.entry(key)
if entry:
return entry.values[index]
else:
return default
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 = []
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 list(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 list(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)
# -*- coding: utf-8 -*-
import os
import dbus
import glob
import scom
from sorg import consts
from sorg.utils import *
sysdir = "/sys/bus/pci/devices/"
class Output:
def __init__(self, name):
self.name = name
self.enabled = True
self.ignored = False
self.__reset()
def __reset(self):
self.mode = ""
self.refresh_rate = ""
self.rotation = ""
self.right_of = ""
self.below = ""
def setEnabled(self, enabled):
self.enabled = enabled
if enabled:
self.ignored = False
else:
self.__reset()
def setIgnored(self, ignored):
self.ignored = ignored
if ignored:
self.enabled = False
self.__reset()
def setMode(self, mode, rate=""):
self.mode = mode
self.refresh_rate = rate
def setOrientation(self, rotation, reflection=""):
if rotation not in ("inverted", "left", "right"):
rotation = ""
self.rotation = rotation
def setPosition(self, pos, arg):
if pos == "RightOf":
self.right_of = arg
self.below = ""
elif pos == "Below":
self.right_of = ""
self.below = arg
else:
self.right_of = ""
self.below = ""
class VideoDevice:
def __init__(self, deviceDir=None, busId=None):
if deviceDir:
self.bus = tuple(int(x, 16) for x in deviceDir.replace(".",":").split(":"))[1:4]
else:
self.bus = tuple(int(x) for x in busId.split(":")[1:4])
deviceDir = "0000:%02x:%02x.%x" % self.bus
self.bus_id = "PCI:%d:%d:%d" % self.bus
self.vendor_id = lremove(pciInfo(deviceDir, "vendor"), "0x").lower()
self.product_id = lremove(pciInfo(deviceDir, "device"), "0x").lower()
self.saved_vendor_id = None
self.saved_product_id = None
self.driver = None
self.depth = 0
self.outputs = {}
self.monitors = {}
def driverInfo(self, driver=None):
if driver is None:
driver = self.driver
if driver is None:
return {}
link = scom.Link()
packages = list(link.Xorg.Driver)
for package in packages:
try:
info = link.Xorg.Driver[package].getInfo()
except dbus.DBusException:
continue
alias = str(info["alias"])
if alias == driver:
info["package"] = package
return info
else:
if driverExists(driver):
info = {
"alias": driver,
"xorg-module": driver,
}
return info
else:
return {}
def setDriver(self, driver):
"""
Change driver.
Driver name can be an alias like "nvidia173". If needed,
the driver is enabled.
"""
self.driver = driver
self.outputs = {}
self.enableDriver()
def enableDriver(self):
package = self.driverInfo().get("package")
oldpackage = enabledPackage()
if package != oldpackage:
link = scom.Link()
if oldpackage and oldpackage.replace("-", "_") in list(link.Xorg.Driver):
link.Xorg.Driver[oldpackage].disable(timeout=2**16-1)
if package:
link.Xorg.Driver[package].enable(timeout=2**16-1)
def preferredDriver(self, installed=True):
if isVirtual():
return "fbdev" if os.path.exists("/dev/fb0") else None
cardId = self.vendor_id + self.product_id
for line in loadFile(consts.drivers_file):
if line.startswith(cardId):
driver = line.split()[1]
if installed:
drvInfo = self.driverInfo(driver)
if not drvInfo:
return None
return driver
def isChanged(self):
if self.saved_vendor_id and self.saved_product_id:
return (self.vendor_id, self.product_id) != (self.saved_vendor_id, self.saved_product_id)
return False
class Monitor:
def __init__(self):
self.vendor = ""
self.model = "Default Monitor"
self.hsync = "31.5-50"
self.vref = "50-70"
def pciInfo(dev, attr):
return sysValue(sysdir, dev, attr)
def getKeymapList():
return os.listdir(consts.xkb_symbols_dir)
def driverExists(name):
return os.path.exists(os.path.join(consts.drivers_dir, "%s_drv.so" % name))
def listAvailableDrivers(d = consts.drivers_dir):
a = []
if os.path.exists(d):
for drv in os.listdir(d):
if drv.endswith("_drv.so"):
if drv[:-7] not in a:
a.append(drv[:-7])
return a
def enabledPackage():
try:
return file("/var/lib/sorg/enabled_package").read()
except IOError:
return None
def getPrimaryCard():
for boot_vga in glob.glob("%s/*/boot_vga" % sysdir):
if open(boot_vga).read().startswith("1"):
dev_path = os.path.dirname(boot_vga)
return os.path.basename(dev_path)
return None
# -*- coding: utf-8 -*-
import os
import subprocess
from pardus.sysutils import get_kernel_option
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):
def rename_backup(src, n):
if n == 4:
return
new_name = "%s-backup%d" % (_file, n)
if os.path.exists(new_name):
rename_backup(new_name, n+1)
try:
os.rename(src, new_name)
except IOError:
pass
if os.path.exists(_file):
backup_file = "%s-backup" % _file
if os.path.exists(backup_file):
rename_backup(backup_file, 2)
try:
os.rename(_file, backup_file)
except IOError:
pass
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 idsQuery(vendor, device, idsFile="/usr/share/misc/pci.ids"):
f = file(idsFile)
flag = 0
company = "Unknown Company"
model = "Unknown Model"
for line in f.readlines():
if flag == 0:
if line.startswith(vendor):
flag = 1
company = line[5:].strip()
else:
if line.startswith("\t"):
if line.startswith("\t" + device):
model = line[6:].strip()
break
elif not line.startswith("#"):
flag = 0
return company, model
def xisrunning():
return os.path.exists(xorg_lock)
def isVirtual():
# Xen detection
if os.path.exists("/proc/xen/capabilities"):
# we are in dom0, act like normal system
if loadFile("/proc/xen/capabilities") == []:
# and in domU, configure X to use fbdev if exists
return True
return False
def jailEnabled():
xorg_options = get_kernel_option("xorg")
if not "nojail" in xorg_options:
if "thin" in get_kernel_option("mudur") or "jail" in xorg_options:
print("Jail is enabled")
return True
return False
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