You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
calculate-utils-3-console-gui/consolegui/application/ConnectionTabs.py

538 lines
19 KiB

12 years ago
#!/usr/bin/python
#-*- coding: utf-8 -*-
import dbus
import dbus.service
import dbus.mainloop.glib
12 years ago
from PySide import QtGui, QtCore
import sudsds, time, sys
import os, pwd, shutil
import ConfigParser
12 years ago
from TrayIcon import TrayIcon
from more import get_sid, get_view_params
12 years ago
from MainClass import ApiClient
from calculate.consolegui.datavars import DataVarsGui
from pid_information import client_pid_info
#from calculate.lib.cl_lang import setLocalTranslate
#setLocalTranslate('console_gui',sys.modules[__name__])
12 years ago
class SelectedMethodWgt(QtGui.QWidget):
def __init__(self, app, args):
QtGui.QWidget.__init__(self)
self.args = args
self.user_changed_flag = False
self.lang = args.lang
self.method = args.method
# Initialization GUI variables
self.VarsGui = DataVarsGui()
self.VarsGui.importGui()
self.VarsGui.flIniFile()
self.ClientObj = ApiClient(app, self)
self.MethodWidget = self.ClientObj.MainWidget
self.MethodWidget.topmenu.hide()
layout = QtGui.QHBoxLayout(self)
layout.setContentsMargins(0,0,0,0)
layout.setSpacing(0)
layout.addWidget(self.MethodWidget)
QtGui.QIcon.setThemeName('Calculate')
self.setWindowIcon(QtGui.QIcon \
('/usr/share/pixmaps/calculate-console-online.png'))
if self.connect():
sys.exit(1)
if not self.get_size():
# definition of screen resolution
prim_screen = app.desktop().primaryScreen()
d_size = app.desktop().screenGeometry(prim_screen).size()
# resize main widget
if d_size.height() < 768:
self.resize(900,560)
else:
self.resize(900, 726)
self.setMinimumHeight(100)
self.setMinimumWidth(500)
self.show()
def connect(self):
self.MethodWidget.connect_to_localhost(self.args.host, self.args.port)
if not self.ClientObj.client:
return 1
self.ClientObj.sid = get_sid(self.ClientObj.client)
try:
view_params = get_view_params(self.ClientObj.client, \
self.args.method + '_view', step = 0)
12 years ago
view = self.ClientObj.client.service[0][self.args.method + \
'_view'](int(self.ClientObj.sid), view_params)
except sudsds.MethodNotFound:
12 years ago
_print ('Method not found: ', self.args.method + '_view')
self.close()
sys.exit(1)
if self.ClientObj.method_names.has_key(self.args.method):
view_method = self.ClientObj.method_names[self.args.method]
else:
view_method = self.args.method
self.setWindowTitle(view_method + ' - ' + \
self.ClientObj._parent.windowTitle())
self.MethodWidget.main_frame_view(view, self.args.method)
return 0
def translate(self, lang = None):
return 0
def connect_count_changed(self, host, port, count):
pass
def get_size(self):
conf_path = self.VarsGui.Get('cl_gui_config_path')
homePath = self.VarsGui.Get('ur_home_path')
self.user_config = conf_path.replace("~",homePath)
self.config = ConfigParser.ConfigParser()
self.config.read(self.user_config)
try:
size = self.config.get('gui', 'size')
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
return False
tup_size = map(lambda x: int(x), size.split(','))
self.resize(tup_size[0], tup_size[1])
return True
def set_size(self):
self.config = ConfigParser.ConfigParser()
self.config.read(self.user_config)
try:
self.config.set('gui', 'size', ','.join(map(lambda x: str(x),
self.size().toTuple())))
self.config.write(open(self.user_config, 'w'))
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
return False
def closeEvent(self, event):
close_event = self._closeEvent()
# event.ignore()
if close_event:
self.set_size()
save_path = os.path.join('/tmp', 'calculate-' + \
pwd.getpwuid(os.getuid()).pw_name)
if os.path.isdir(save_path):
shutil.rmtree(save_path)
event.accept()
else:
event.ignore()
def _closeEvent(self):
if not self.isVisible():
if self.ClientObj.signaling.isRunning():
self.ClientObj.signaling.close()
self.ClientObj.signaling.wait()
return 1
if not self.user_changed_flag:
reply = QtGui.QMessageBox.Yes
else:
reply = self.show_close_messagebox()
from mainframe import MainFrame
if reply == QtGui.QMessageBox.Yes:
if hasattr (self, 'con_lost_lbl'):
self.con_lost_lbl.hide()
self.con_lost_lbl.close()
# Exit with closing session
if self.ClientObj.signaling.isRunning():
self.ClientObj.signaling.close()
self.ClientObj.signaling.wait()
if type (self.MethodWidget.MainFrameWgt) == MainFrame:
return 1
else:
pid = int(self.MethodWidget.MainFrameWgt.cur_pid)
self.MethodWidget.MainFrameWgt.close()
self.ClientObj.client.service.pid_kill(pid, self.ClientObj.sid)
while True:
client_pid_info(self.ClientObj, self.ClientObj.client, 0)
if not self.ClientObj.process_dict[str(pid)].has_key \
('status'):
return 1
if self.ClientObj.process_dict[str(pid)]['status'] != '1':
return 1
time.sleep(1)
elif reply == QtGui.QMessageBox.No:
return 0
def user_changed(self):
self.user_changed_flag = True
def show_close_messagebox(self):
msgBox = QtGui.QMessageBox(self)
if self.ClientObj.method_names.has_key(self.method):
method_name = self.ClientObj.method_names[self.method]
else:
method_name = self.method
msgBox.setText(_("Close") +' "%s"?' %method_name)
msgBox.setStandardButtons(QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
# translate
msgBox.button(msgBox.Yes).setText(_('Yes'))
msgBox.button(msgBox.No).setText(_('No'))
if QtGui.QIcon.hasThemeIcon('dialog-close'):
msgBox.button(msgBox.No).setIcon \
(QtGui.QIcon.fromTheme('dialog-close'))
msgBox.setDefaultButton(QtGui.QMessageBox.No)
msgBox.setWindowIcon(QtGui.QIcon.fromTheme("application-exit"))
reply = msgBox.exec_()
return reply
def parse():
import gettext
try:
set_lang = gettext.locale.getdefaultlocale()[0][:2]
12 years ago
lang = gettext.translation('cl_consolegui3', languages=[set_lang],fallback=True)
try:
lang.install(unicode=True)
except UnboundLocalError:
pass
except (IOError, TypeError):
pass
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
'-h', '--help', action='store_true', default=False,
dest='help', help=_("show this help message and exit"))
parser.add_argument(
'-l', '--lang', type=str, dest='lang',
12 years ago
help=_("translation language"))
parser.add_argument(
'--method', type=str, dest='method',
help=_('call method'))
parser.add_argument(
'-p', '--port', type=int, default = '8888', dest='port',
help=_('port number'))
parser.add_argument(
'--host', type=str, default = 'localhost', dest='host',
12 years ago
help=_('destination host'))
return parser
class DBusWidget(dbus.service.Object):
def __init__(self, name, session, parent):
self._parent = parent
# export this object to dbus
dbus.service.Object.__init__(self, name, session)
# You can export methods to dbus like you do in python-dbus.
@dbus.service.method("org.calculate.consolegui", in_signature='', \
out_signature='')
def show(self):
self._parent.showNormal()
12 years ago
class MyTabBar(QtGui.QTabBar):
def __init__(self, _parent):
12 years ago
QtGui.QTabBar.__init__(self)
self._parent = _parent
12 years ago
def wheelEvent(self, event):
event.ignore()
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.MouseButton.LeftButton:
self.setCurrentIndex(self.tabAt(event.pos()))
event.accept()
if event.button() == QtCore.Qt.MouseButton.MiddleButton:
self._parent.close_tab(self.tabAt(event.pos()))
12 years ago
class ToolTabWidget(QtGui.QTabWidget):
12 years ago
def __init__(self, app, args = None, host = None, port = None):
12 years ago
QtGui.QTabWidget.__init__(self)
self.app = app
12 years ago
if args:
if args.lang:
self.lang = args.lang
12 years ago
self.setContentsMargins(0,0,0,0)
12 years ago
self.init_variables()
12 years ago
# Initialization GUI variables
self.VarsGui = DataVarsGui()
self.VarsGui.importGui()
self.VarsGui.flIniFile()
12 years ago
ClientObj = ApiClient(app, self)
self.FirstWidget = ClientObj.MainWidget
12 years ago
12 years ago
self.PlusWidget = QtGui.QWidget(self)
12 years ago
self.tabbar = MyTabBar(self)
self.setTabBar(self.tabbar)
12 years ago
QtGui.QIcon.setThemeName('Calculate')
12 years ago
self.gui_icon = QtGui.QIcon.fromTheme("video-display")
12 years ago
12 years ago
self.other_icon = QtGui.QIcon.fromTheme("list-add")
if self.other_icon.isNull():
self.other_icon = QtGui.QIcon.fromTheme("preferences-desctop")
12 years ago
12 years ago
self.addTab(self.FirstWidget, self.gui_icon , self.new_con_txt)
self.addTab(self.PlusWidget, self.other_icon, '')
12 years ago
12 years ago
self.last_close_index = -1
self.tabCloseRequested.connect(self.close_tab)
self.selected.connect(self.add_tab)
12 years ago
12 years ago
self.selected.connect(self.changeWindowTitle)
12 years ago
12 years ago
self.setTabsClosable(True)
self.tabbar.tabButton(1, QtGui.QTabBar.ButtonPosition.RightSide).hide()
12 years ago
if not self.get_size():
# definition of screen resolution
prim_screen = self.app.desktop().primaryScreen()
d_size = self.app.desktop().screenGeometry(prim_screen).size()
# resize main widget
if d_size.height() < 768:
self.resize(900,560)
else:
self.resize(900, 700)
self.setMinimumHeight(100)
self.setMinimumWidth(500)
12 years ago
self.setWindowTitle(self.Name)
self.setStyleSheet('''
QTabBar::tab:last {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
border: 2px solid #C4C4C3;
border-bottom-color: #C2C7CB; border-top-left-radius: 4px;
border-top-right-radius: 4px; padding-left: 3px;
margin-left: 3px; margin-bottom: 5px; margin-top: 2px; width: 18px;}
QTabBar::tab:last::hover {background:
qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #E9E9E9, stop: 0.4 #E5E5E5,
stop: 0.5 #E1E1E1, stop: 1.0 #DDDDDD);}
''')
self.setWindowIcon(QtGui.QIcon \
12 years ago
('/usr/share/pixmaps/calculate-console-offline.png'))
12 years ago
12 years ago
self.show()
self.app.processEvents()
12 years ago
self.connect_dict = {}
self.connect_count = 0
if not host or host == 'localhost':
host = '127.0.0.1'
self.FirstWidget.connect_to_localhost(host, port)
if self.FirstWidget.ClientObj.client:
if host in ['127.0.0.1', 'localhost']:
self.localhost_ClientObj = self.FirstWidget.ClientObj
if not host in self.connect_dict:
self.connect_dict[host] = [port]
else:
if port:
if not port in self.connect_dict[host]:
self.connect_dict[host].append(port)
self.create_tray()
12 years ago
if self.FirstWidget.ClientObj.client:
self.tray.set_icon(True)
def connect_count_changed(self, host, port, count):
if count:
if not host in self.connect_dict:
self.connect_dict[host] = [port]
else:
if port:
if not port in self.connect_dict[host]:
self.connect_dict[host].append(port)
else:
if host in self.connect_dict:
if port in self.connect_dict[host]:
self.connect_dict[host].remove(port)
if not self.connect_dict[host]:
self.connect_dict.pop(host)
if self.connect_dict:
self.setWindowIcon(QtGui.QIcon \
12 years ago
('/usr/share/pixmaps/calculate-console-online.png'))
if hasattr(self, 'tray'):
self.tray.set_icon(True)
else:
self.setWindowIcon(QtGui.QIcon \
12 years ago
('/usr/share/pixmaps/calculate-console-offline.png'))
if hasattr(self, 'tray'):
self.tray.set_icon(False)
12 years ago
def init_variables(self):
try:
self.Version = self.VarsGui.Get('cl_ver')
12 years ago
except:
self.Version = ''
12 years ago
try:
self.Name = self.VarsGui.Get('cl_name')
12 years ago
except:
self.Name = 'Calculate Console'
12 years ago
self.new_con_txt = _('New connection')
self.sys_update_pid = None
12 years ago
def close_tab(self, cur_num = None, hard = False):
exit_flag = 0
12 years ago
if cur_num == None:
cur_num = self.currentIndex()
if cur_num != self.count() - 1:
# for delete widget
self.setCurrentIndex(cur_num)
wgt = self.currentWidget()
12 years ago
if wgt == self.FirstWidget and not hard:
return exit_flag
12 years ago
if wgt._closeEvent():
wgt.close()
12 years ago
self.last_close_index = cur_num
if cur_num:
self.setCurrentIndex(cur_num - 1)
else:
self.setCurrentIndex(0)
self.removeTab(cur_num)
exit_flag = 1
if self.count() < 2:
12 years ago
self.add_tab()
return exit_flag
12 years ago
def add_tab(self):
if self.currentIndex() == self.count() - 1:
# not add if exists clean tab
for tab_num in range(self.count() - 1):
self.setCurrentIndex(tab_num)
if not self.currentWidget().ClientObj.client:
return 0
12 years ago
ClientObj = ApiClient(self.app, self)
widget = ClientObj.MainWidget
widget.cur_window_title = self.Name
12 years ago
self.insertTab(self.count() - 1, widget, self.gui_icon , \
self.new_con_txt)
self.setCurrentIndex(self.count() - 2)
if self.currentWidget().ClientObj.client:
self.tabbar.setTabEnabled(self.count() - 1, True)
else:
self.tabbar.setTabEnabled(self.count() - 1, False)
12 years ago
def rename_tab(self, text = None, ind = None):
if not text:
text = self.new_con_txt
if not ind:
ind = self.currentIndex()
self.setTabText(ind, text)
12 years ago
def changeWindowTitle(self, tab_num):
try:
text = self.currentWidget().cur_window_title
self.setWindowTitle(text)
except AttributeError:
pass
12 years ago
def setWindowTitle(self, title):
self.currentWidget().cur_window_title = title
super(ToolTabWidget, self).setWindowTitle(title)
12 years ago
def create_tray(self):
self.tray = TrayIcon(self)
self.tray.setVisible(True)
self.app.processEvents()
12 years ago
def translate(self, lang = None):
12 years ago
self.new_con_txt = _('New connection')
self.new_con_txt = self.new_con_txt.decode('utf-8')
current = self.currentIndex()
# not add if exists clean tab
for tab_num in range(self.count() - 1):
self.setCurrentIndex(tab_num)
if not self.currentWidget().ClientObj.client:
self.setTabText(tab_num, self.new_con_txt)
self.setCurrentIndex(current)
if hasattr(self, 'tray'):
self.tray.translate()
12 years ago
def set_localhost(self, ClientObj):
self.localhost_ClientObj = ClientObj
# if ClientObj:
# self.connect_dict[ClientObj.host_name] = \
# [ClientObj, self.currentIndex()]
# self.tabbar.tabButton(self.currentIndex(), \
# QtGui.QTabBar.ButtonPosition.RightSide).hide()
def find_host(self, host_name, port):
ind = self.currentIndex()
for i in xrange (self.count() - 1):
self.setCurrentIndex(i)
wgt = self.currentWidget()
if hasattr (wgt, 'ClientObj'):
ClientObj = wgt.ClientObj
if host_name == ClientObj.host_name and \
port == ClientObj.port and ClientObj.client:
self.removeTab(ind)
return 1
self.setCurrentIndex(ind)
return 0
12 years ago
def closeEvent(self, event):
self.cur_pos = self.pos()
self.hide()
event.ignore()
def _closeEvent(self):
for tab_num in range(self.count()):
if not self.close_tab(0, True):
return 1
self.set_size()
save_path = os.path.join('/tmp', 'calculate-' + \
pwd.getpwuid(os.getuid()).pw_name)
if os.path.isdir(save_path):
shutil.rmtree(save_path)
self.app.exit()
def get_size(self):
conf_path = self.VarsGui.Get('cl_gui_config_path')
homePath = self.VarsGui.Get('ur_home_path')
self.user_config = conf_path.replace("~",homePath)
self.config = ConfigParser.ConfigParser()
self.config.read(self.user_config)
try:
size = self.config.get('gui', 'size')
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
return False
tup_size = map(lambda x: int(x), size.split(','))
self.resize(tup_size[0], tup_size[1])
return True
def set_size(self):
self.config = ConfigParser.ConfigParser()
self.config.read(self.user_config)
try:
self.config.set('gui', 'size', ','.join(map(lambda x: str(x),
self.size().toTuple())))
self.config.write(open(self.user_config, 'w'))
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
return False
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Return:
self.currentWidget().keyPressEvent(e)
else:
QtGui.QTabWidget.keyPressEvent(self, e)